關於小程式&VUE上傳檔案的java處理方法
阿新 • • 發佈:2019-01-05
簡述
相關文章有很多,在此記錄一下用起來個人一直在用的一種方式:使用servlet來獨立處理檔案上傳,獲取前端的檔案之後向CDN同步,最後返回檔案的最終相對路徑,由前端訪問CDN服務來展示圖片;
使用servlet的方便性在於可以跟專案實現零耦合,方便快速移植。
好了,廢話不多說,直接上程式碼,註釋都在程式碼裡了;
java處理servlet
package com.TVMall.web.filter;
import com.TVMall.core.util.FileUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Project:
*
* File: MicroSoftUpLoadFilter
*
* Description: 小程式&VUE formData上傳圖片servlet
*
* @author : MikeLC
*
* @date: 2017/11/14 上午 10:04
*
* Copyright ( c ) 2017
*
*/
public class MicroSoftUpLoadFilter extends HttpServlet {
private static final long serialVersionUID = 1L;
//檔案目錄
private String uploadFilePath = "D:\\temp";
File tempFile;
//列印日誌
protected Log logger = LogFactory.getLog(this.getClass());
/**
* @see HttpServlet#HttpServlet()
*/
public MicroSoftUpLoadFilter() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(4096);//緩衝區大小
factory.setRepository(tempFile);//緩衝區目錄
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(4194304);//最大檔案尺寸,4MB
SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String resultPath = "";
List<String> ressultPathList = new ArrayList<String>();
String relatePath = "";
try {
List<FileItem> fileItems = upload.parseRequest(request);
Iterator<FileItem> i = fileItems.iterator();
boolean flag = false;//判斷recordId是否為空
String value = "";
while(i.hasNext()){
FileItem fileItem = i.next();
String fileName = fileItem.getName();
if (fileItem.getFieldName() != null) {//formData中的資料
if (fileItem.isFormField()) {//一般的表單域,即獲取formData中的引數
value = fileItem.getString("utf-8");
System.out.println(value);
if (StringUtils.isEmpty(value)) {
flag = true;
}
//
if(fileItem.getFieldName().equals("relatePath")){
relatePath = value;
}
}
}
//
if(fileName != null){
String path = FileUtil.buildImgPath(request,relatePath);
String realPath = request.getRealPath(path);
File filePath = new File(realPath);
if (!filePath.exists()) {
try {
filePath.mkdirs();
} catch (Exception e) {
e.printStackTrace();
}
}
File file = new File(filePath + "/" + fileName);
fileItem.write(file);
//同步
FileUtil.sendFileOperate(file,request,relatePath);
//
resultPath = path +"/"+ fileName;
ressultPathList.add(resultPath);
}
}
//
//byte[] jsonStr = JSON.toJSONBytes(ressultPathList);
byte[] jsonStr = resultPath.getBytes();
response.setHeader("Content-type", "text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
//response.getOutputStream().write(jsonStr);
//
PrintWriter pw = response.getWriter();
pw.write(resultPath);
System.out.println("upload success");
} catch (Exception e) {
e.printStackTrace();
logger.info("upload throw exception!");
}
}
}
配置servlet
<!-- 圖片上傳 -->
<servlet>
<description></description>
<display-name>MicroSoftUpLoadFilter</display-name>
<servlet-name>MicroSoftUpLoadFilter</servlet-name>
<servlet-class>com.TVMall.web.filter.MicroSoftUpLoadFilter</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MicroSoftUpLoadFilter</servlet-name>
<url-pattern>/wxUpload/*</url-pattern>
</servlet-mapping>
前端程式碼
微信小程式
wx.uploadFile({
url: 'https://xxxxxx/upload/tongue',
filePath: filePath,//圖片路徑,如tempFilePaths[0]
name: 'image',
header : {
"Content-Type": "multipart/form-data"
},
formData:
{
userId: 12345678 //附加資訊為使用者ID
},
success: function (res) {
console.log(res);
},
fail: function (res) {
console.log(res);
},
complete: function (res) {
}
})
Vue
<script>
export default {
name : 'MoUpload',
props : {
accepts : { //允許的上傳型別
type : String,
default : 'image/jpeg,image/jpg,image/png,image/gif'
},
flag : [String, Number], //當前上傳標識,以便於在同一個監聽函式中區分不同的上傳域
maxSize : {
type : Number,
default : 0 //上傳大小限制
},
},
methods: {
upload (event) {
let file = event.target.files[0]
const self = this
const flag = this.flag
if (file) {
if (this.maxSize) {
//todo filter file
}
//filter file, 檔案大小,型別等過濾
//如果是圖片檔案
// const reader = new FileReader()
// const imageUrl = reader.readAsDataURL(file)
// img.src = imageUrl //在預覽區域插入圖片
const formData = new FormData()
formData.append('file', file)
//獲取token
this.$http.get(`/api/token/`)
.then(response => {
const result = response.body
formData.append('token', result.token)
formData.append('key', result.key)
//提交給七牛處理
self.$http.post('https://up.qbox.me/', formData, {
progress(event) {
//傳遞給父元件的progress方法
self.$emit('progress', parseFloat(event.loaded / event.total * 100), flag)
}
})
.then(response => {
const result = response.body
if (result.hash && result.key) {
//傳遞給父元件的complete方法
self.$emit('complete', 200 , result, flag)
//讓當前target可以重新選擇
event.target.value = null
} else {
self.$emit('complete', 500, result, flag)
}
}, error => self.$emit('complete', 500, error.message), flag)
})
}
}
}
}
</script>
推薦文章
在研究Vue的上傳中,這篇文章描述的很細緻,強烈推薦;