這裏介紹一下工作中做上傳圖片的體會,工作中是將選擇圖片之後異步上傳到服務器,返回一個在服務器保存的圖片路徑,然後賦值到一個隱藏域裏,提交表單的時候,再去執行存數據庫的操作。
個人感覺這種上傳圖片的方式要比把表單數據和圖片一起提交要好一點。
直接來看代碼,這裏只展示controller層
import cn.util.DateUtils;
import cn.util.ResponseResult;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Controller層
* @author Rhine
*
*/
@Controller
@RequestMapping("api/file/")
public class UploadController {
/**
* 異步上傳圖片
* @param files
* @return
* @throws IOException
* @throws IllegalStateException
* ResponseResult 是自己定義的返回值對象,可隨便定義
*/
@RequestMapping(value = "upload",method = RequestMethod.POST)
@ResponseBody
public ResponseResult uploadFiles(@RequestParam("files") MultipartFile[] files, HttpServletRequest request) throws IllegalStateException, IOException {
//支持多圖片上傳
String result = "";
for(int i=0;i<files.length;i++){
if (!files[i].isEmpty()) {
//獲得原始文件名;
String fileRealName = files[i].getOriginalFilename();
//根據圖片名稱獲取一個hash值,算出來的值作爲文件路徑
/**********************************************/
int hashcode = fileRealName.hashCode();//得到hashCode
int dir1 = hashcode & 0xf; //得到名爲1到16的下及文件夾
int dir2 = (hashcode & 0xf0) >> 4; //得到名爲1到16的下下及文件夾
//獲取服務器指定文件存取路徑,我的fileupload在webapp下
String savedDir = request.getSession().getServletContext().getRealPath("fileupload");
String dir = savedDir + "/" + dir1 + "/" + dir2; //得到文件路徑
/****************************************************/
//點號的位置
int pointIndex = fileRealName.indexOf(".");
//截取文件後綴
String fileSuffix = fileRealName.substring(pointIndex);
String filePreName="";
//獲取文件名不帶後綴名
filePreName=fileRealName.substring(0,fileRealName.lastIndexOf("."));
String date = DateUtils.getDate("yyyyMMddHHmmss");
//文件存取名
String savedFileName = filePreName + "_" +date.concat(fileSuffix);
File file2 = new File(dir); //創建文件夾 如果不存在
if(!file2.exists()){
file2.mkdirs();
System.out.println(dir);
System.out.println("創建文件夾成功======================"+dir);
}
File savedFile = new File(dir,savedFileName );
boolean isCreateSuccess = savedFile.createNewFile();
if(isCreateSuccess){
files[i].transferTo(savedFile); //轉存文件
}
String filepath = "/fileupload/" + dir1 + "/" + dir2+ "/" +savedFileName;
result = result+ filepath + ",";
}
}
//多個文件以逗號分隔,然後去掉最後一個逗號
result = result.substring(0,result.length()-1);
return ResponseResult.ok(result);
}
}
前端調用之後,返回一個字符串,多個圖片路徑以逗號分隔開。