如何通过ajax实现文件上传-java文件传输

如何通过ajax实现文件上传-java文件传输

大噶好,今天我们先简单的来了解一个非常实用的功能,通过ajax上传文件。

技能:vue + axios + servlet

视图

<div id="app" >

<input type="file" @change="uploadPimage" name="upload" />

</div>

vue.js

<script type="application/javascript" src="https://www.shangyouw.cn${ pageContext.request.contextPath }/js/vue.js"></script>
<script type="application/javascript" src="https://www.shangyouw.cn${ pageContext.request.contextPath }/js/axios.min.js"></script>
<script type="application/javascript" >
var vue = new Vue({
el: "#app",
data:{
pimage:""
}
},
methods:{
uploadPimage:function (event) {

//通过ajax 上传文件
var formData = new FormData();
formData.append("pimage",event.target.files[0]);
axios({
url:"https://www.shangyouw.cn${ pageContext.request.contextPath }/AdminProductServlet?method=uploadPimage",
method: 'post',
headers:{
'Content-Type': 'multipart/form-data'
},
data:formData
}).then(function (resp) {
//将服务器的图片地址 赋给 product.pimage
vue.pimage = resp.data;
})
}
}
})
</script>

核心的知识就是通过 FormData对象模拟一个form表单数据,我们知道表单提交必须设置表单属性enctype="multipart/form-data",并且提交方式为post。所以我们在通过axios提交数据时,需要设置请求头'Content-Type': 'multipart/form-data'。

Servlet代码

 public String uploadPimage(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
Part uploadPart = request.getPart("pimage");
//获取文件名(来自于请求头 Content-Disposition: form-data; name="upload"; filename="big.webp")
String contentDisposition = uploadPart.getHeader("Content-Disposition");
int beginIndex = contentDisposition.indexOf("filename=\"") + 10;
String fileName = contentDisposition.substring(beginIndex).replaceAll("\"", "");
if (!fileName.isEmpty()) {
fileName = "products/1/" + UuidUtils.getUUID() + fileName;
String filePath = request.getServletContext().getRealPath("/") + fileName;
//获取字节流
InputStream inputStream = uploadPart.getInputStream();
OutputStream outputStream = new FileOutputStream(filePath);
//保存文件
IOUtils.copy(inputStream, outputStream);
}
//向前端响应 文件名
return fileName;
}

好,搞定。

推荐阅读