前端小程式代碼:
function send_photo(data, successfun) {
var that = this
console.log("data長度=" + data.length)
console.log("data路徑=" + data[0] + "")
wx.uploadFile({
url: '************************************upload.action', //僅為示例,非真實的介面地址 自己寫映射你Java介面的路徑
header: { "Content-Type": "multipart/form-data" },
filePath: data[0] + "",
name: 'file',
formData:{
method: 'POST'
},
success: function(res) {
successfun(res)
}
})
}
后臺java接收代碼:
public void upload() throws Exception {
try {
Date date = new Date();
// 上傳檔案
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(4096); // 設定緩沖區大小,這里是4kb
String basePath = ServletActionContext.getRequest().getRealPath("/");// 獲取根目錄
// 設定下載目錄
String uploadPath = basePath + "/upload";
// 設定臨時目錄
String tempPath = uploadPath + "/temp";
// uploadPath = uploadPath +"/"+ date.getTime();//添加時間目錄防止重復
this.initDir(uploadPath, tempPath);
File tempPathFile = new File(tempPath);
factory.setRepository(tempPathFile);// 設定緩沖區目錄
ServletFileUpload upload = new ServletFileUpload(factory);
// upload.setSizeMax(34194304); 設定最大檔案尺寸,4MB
List items = upload.parseRequest(request);// 得到所有的檔案
Iterator itr = items.iterator();
String imgUrl;
while (itr.hasNext()) {
FileItem fileItem = (FileItem) itr.next();
if (fileItem.isFormField()) {
System.out.println("表單引數名:" + fileItem.getFieldName() + ",表單引數值:" + fileItem.getString("utf-8"));
} else {
if (fileItem.getName() != null && !"".equals(fileItem.getName())) {
System.out.println("上傳檔案的大小:" + fileItem.getSize());
System.out.println("上傳檔案的型別:" + fileItem.getContentType());
System.out.println("上傳檔案的名稱:" + fileItem.getName());
// 保存檔案
File saveFile = new File(uploadPath, fileItem.getName());
fileItem.write(saveFile);
imgUrl = uploadPath + "/" + fileItem.getName();
System.out.println("上傳成功");
} else {
System.out.println("沒有上傳檔案");
}
}
}
Writer out = response.getWriter();
out.write("success");
out.flush();
} catch (Exception e) {
e.printStackTrace();
throw new Exception(e);
}
}
大于2M的檔案能夠成功接收,那配置是正確的,代碼也應該是正確的。本例tomcat 8.0,jdk1.8。
uj5u.com熱心網友回復:
是小于2M的不成功嗎?uj5u.com熱心網友回復:
為什么不用spring boot?可以在網關端就設定檔案上傳的大小,包括單個檔案大小和總大小都可以設定,不需要些到代碼里,方便維護。uj5u.com熱心網友回復:
也可以通過nginx轉發的時候,限制檔案大小的。寫到代碼里面后期維護更新很麻煩。轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/59173.html
標籤:Web 開發
