一、vue 前端处理
1、vue 图片上传方法,要将图片转成base64,并加文件名,cropper 中的name要与formData.append('uploadFile', blob, nameImg)对应,最好用uploadFile
handleCroped (blob) {
let that = this
const formData = new FormData()
// 转化成png格式
const nameImg = new Date().getTime() + '.png'
formData.append('uploadFile', blob, nameImg)
upload(formData).then(res => {
if (res.status === 200 && res.data.state === 200) {
this.$Message.success('上传成功')
that.cropperModal = false
} else {
that.$Message.error(res.data.message)
}
}).catch(function (error) {
console.log(error)
})
},
2、找到/libs/axios.js,此处的目的是将http请求头设置成"multipart/form-data格式,不然后端会报 The current request is not a multipart request 错误,因为我之前是将POST传参序列化, json格式转成formdata格式 所以此处需要特殊处理下
interceptors (instance, url) {
// 请求拦截
instance.interceptors.request.use(config => {
// 添加全局的loading...
if (!Object.keys(this.queue).length) {
// Spin.show() // 不建议开启,因为界面不友好
}
// POST传参序列化, json格式转成formdata格式 qs是axios自带的模块
if (config.method === 'post' && config.url !== 'file/upload') {
config.data = qs.stringify(config.data)
}
// 图片上传需要变成 multipart/form-data 格式
if(config.url === 'file/upload'){
config.headers.post["Content-Type"] = "multipart/form-data"
}
this.queue[url] = true
return config
}, error => {
return Promise.reject(error)
})
// 响应拦截
instance.interceptors.response.use(res => {
this.destroy(url)
const { data, status } = res
return { data, status }
}, error => {
this.destroy(url)
let errorInfo = error.response
if (!errorInfo) {
const { request: { statusText, status }, config } = JSON.parse(JSON.stringify(error))
errorInfo = {
statusText,
status,
request: { responseURL: config.url }
}
}
addErrorLog(errorInfo)
return Promise.reject(error)
})
}
二、java 处理
1、 controller
/* 上传图片 */
@RequestMapping("/upload")
@ResponseBody
public Response upload(@RequestParam("uploadFile") MultipartFile fileUpload) throws Exception {
// 得到图片的原始文件名
String originalName = fileUpload.getOriginalFilename();
// 指定带盘符的路径, 物理路径
String realPath = "F://vfile//images//";
/**
* 为了处理出现重名现象, 将原始文件名去掉,
* 通过UUID算法生成新的文件名
*/
String uuidName = UUID.randomUUID().toString();
// uuid名称加上文件的后缀名
String newFile = uuidName + originalName.substring(originalName.lastIndexOf("."));
// 创建File文件
File file = new File(realPath + newFile);
// 将图片写入到具体的位置
fileUpload.transferTo(file);
// return "redirect:/a";
return new Response(200, "", newFile);
}
2、spring-mvc.xml
<!-- 文件上传 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传文件的最大尺寸为5MB -->
<property name="maxUploadSize">
<value>5242880</value>
</property>
<property name="defaultEncoding">
<value>UTF-8</value>
</property>
</bean>
3、pom.xml 添加依赖
<!--文件上传start-->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<!--文件上传end-->
4、找到项目所在的tomcat下的 /conf/server.xml,配置虚拟路径,磁盘位置最好不要和tomcat位置一致,且不要和其他文件重名
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
prefix="localhost_access_log." suffix=".txt"
pattern="%h %l %u %t "%r" %s %b" />
<Context docBase="F:/vfile/images/" path="/vfile/images" reloadable="true" />
5、tomcat添加映射,不然图片访问报404,步骤图和我自己的实际图
也是踩了一堆坑,总结了前人的经验才知道怎么做的