后台实现
springMVC-servlet.xml
<!-- 设置上传文件最大值 1M=1*1024*1024(B)=1048576 bytes -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="1048576" />
</bean>
controller
@RequestMapping(value = "/upload")
@ResponseBody
public String upload(@RequestParam("filename") MultipartFile file) {
System.out.println("qewqeqwwqe");
if (file.isEmpty()) {
return "文件为空";
}
// 获取文件名
String fileName = file.getOriginalFilename();
// 获取文件的后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
// 文件上传路径
String filePath = "d:/roncoo/ttt/";
// 解决中文问题,liunx 下中文路径,图片显示问题
//fileName = UUID.randomUUID() + suffixName;
File dest = new File(filePath + fileName);
// 检测是否存在目录
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
return "上传成功";
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "上传失败";
}
前台vue
<div>
<input type="file" @change="getFile($event)" /><button @click="upload">文件上传</button>
<div>{{ result }}</div>
<div v-show="uping==1">正在上传中</div>
</div>
export default {
name: 'hello',
data () {
return {
upath: '', //文件上传
result: '',
uping: 0
}
},
methods: {
upload: function () {
//console.log(this.upath);
var zipFormData = new FormData();
zipFormData.append('filename', this.upath);//filename是键,file是值,就是要传的文件,test.zip是要传的文件名
let config = { headers: { 'Content-Type': 'multipart/form-data' } };
this.uping = 1;
this.$http.post('http://localhost:8080/hjsk/upload', zipFormData,config).then(function (response) {
console.log(response);
console.log(response.data);
console.log(response.bodyText);
var resultobj = response.data;
this.uping = 0;
this.result = resultobj.msg;
});
},
getFile: function (even) {
this.upath = event.target.files[0];
}
}
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
</dependency>