Java檔案上傳【通用】
阿新 • • 發佈:2020-12-14
Java檔案上傳 主要是針對於網頁來說,一般是通過input的file型別上傳檔案流到後臺,再通過後臺處理將檔案移動到指定位置達到上傳的目的。
這裡貼程式碼時,主要是以springboot框架為例,但是是通用的。
1、表單提交上傳
<form enctype="multipart/form-data" method="post" action="/upload">
檔案:<input type="file" name=" fileUpload"/>
<input type="submit" value="上傳"/>
</form>
@RequestMapping("/upload")
public String upload(MultipartFile fileUpload) throws IOException{
//獲取檔名
String fileName = fileUpload.getOriginalFilename();
//獲取檔案字尾名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
//重新生成檔名
fileName = UUID.randomUUID()+suffixName;
//指定本地資料夾儲存圖片
String filePath = "D:/idea/IdeaProjects/springbootdemo/src/main/resources/static/";
fileUpload.transferTo(new File(filePath+fileName));
return "index";
}
提交表單的話會重新整理介面,一般不推薦,但這是比較簡單的方法,一般推薦使用ajax提交。
2、ajax提交上傳(FormData)
<script>
function uploadHead() {
var formData = new FormData();
var file = $('#file')[0].files[0];
formData.append("upload",file);
$.ajax({
url:"/uploadHead",
async:true,
processData: false, // jQuery不要去處理髮送的資料
contentType: false, // jQuery不要去設定Content-Type請求頭
type:"POST",
data: formData,
success:function (data) {
if(data=="1"){
alert("上傳成功");
}else{
alert("上傳失敗");
}
},
error:function () {
alert("更新失敗");
},
dataType:"text"
});
}
</script>
<input type="file" name="multipartFile" class="fileInput" id="file" >
<input type="button" onclick="uploadHead();">
//我將上傳檔案做成工具類:
/**
* 上傳檔案
* @param upload
* @param path
* @return
* @throws IOException
*/
public String UploadFile(MultipartFile upload,String path) throws IOException {
//判斷該路徑是否存在
File file = new File(path);
if (!file.exists()) {
//如果這個資料夾不存在的話,就建立這個檔案
file.mkdirs();
}
//獲取上傳檔名稱
String filename = upload.getOriginalFilename();
System.out.println(filename);
//把檔名稱設定成唯一值 uuid 以防止檔名相同覆蓋
String uuid = UUID.randomUUID().toString().replace("-", "");
//新檔名
filename = uuid + "_" + filename;
System.out.println(filename);
//完成檔案上傳
upload.transferTo(new File(path, filename));
String filePath = "upload/" + filename;
return filePath;
}
//這裡的話是已經將檔案上傳並即將圖片記錄在資料庫並更換(mybatis)
@RequestMapping("uploadHead")
public void ReturnHead(HttpServletRequest request, HttpServletResponse response, MultipartFile upload) throws IOException {
User userSession = (User) request.getSession(true).getAttribute("userSession");
OperateFile operateFile = new OperateFile();
if (userSession!=null){
String path = ResourceUtils.getURL("classpath:").getPath() + "static/upload";
//System.out.println(path);
String filePath = operateFile.UploadFile(upload,path);//檔案上傳成功
String filename = upload.getOriginalFilename();
String fileUuid = UUID.randomUUID().toString().replace("-", "");
Img img = new Img();//進行圖片記錄
img.setUuid(fileUuid);
img.setImg_name(filename);
img.setImg_type(1);
img.setImg_path(filePath);
img.setNote(userSession.getUuid()+"使用者上傳");
int c = userService.addImg(img);
if (c>0){
User u1 = new User();
u1.setUuid(userSession.getUuid());
u1.setImg_uuid(fileUuid);
int c1 = userService.updateHead(u1);
if (c1>0){
response.getWriter().write("1");
}else{
response.getWriter().write("0");
}
}else{
response.getWriter().write("0");
}
}
}
注意:獲取當前專案儲存路徑的問題
//一般適用,指當前專案下的upload資料夾下
String path = request.getSession().getServletContext().getRealPath("/upload/");
//springboot比較特殊,需要放在static資料夾下路徑
String path = ResourceUtils.getURL("classpath:").getPath() + "static/upload";