<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="app">
<form>
<input type="file" name="image" @change="onFileChange" />
<input type="button" value="上传" @click="uploadImage()" />
<img :src="imgSrc" width="100"/>
</form>
</div>
</body>
<script src="/vue.js"></script>
<script src="/axios.min.js"></script>
<script type="text/javascript">
axios.defaults.withCredentials = true
new Vue({
el: "#app",
data: {
selectedFile: null,
imgSrc: ''
},
methods: {
//选择文件
onFileChange(e) {
this.selectedFile = e.target.files[0]; //选择的结果是一个文件数组,索引值为0
},
//上传文件
uploadImage() {
const formData = new FormData(); //表单的二进制数据对象
formData.append("image", this.selectedFile); //dog.jpg 文件对象
axios.post("后端地址:端口/api/upload/image", formData, {
Headers: {
'Content-Type': "multipart/form-data"
}
}).then(res => {
this.imgSrc='远程服务器地址:端口/upload/'+res.data
// this.imgSrc='远程服务器地址:端口/upload/1.png'
}).catch(error => {
console.log(error) //发生异常
})
}
}
})
</script>
</html>
依赖
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
<version>1.18.1</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.18.1</version>
</dependency>
@RequestMapping("/image")
public String upLoadImg(@RequestParam("image") MultipartFile myfile) {
String path = "远程服务器地址:端口/upload";
//为上传到服务器的文件取名,使用UUID防止文件名重复
String type = myfile.getOriginalFilename().substring(myfile.getOriginalFilename().lastIndexOf("."));
String filename = UUID.randomUUID().toString() + type;
try {
//使用Jersey客户端上传文件
Client client = Client.create();
WebResource webResource = client.resource(path + "/" + URLEncoder.encode(filename, "utf-8"));
webResource.put(myfile.getBytes());
System.out.println("上传成功");
System.out.println("图片路径==》" + path + filename);
} catch (Exception ex) {
System.out.println("上传失败");
}
return filename;
}