前端采用element
<el-form-item label="头像">
<el-upload
class="avatar-uploader"
action="http://127.0.0.1:8082/upload"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload">
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</el-form-item>
后端
图片文件夹image
package com.example.dpool.controller;
import com.example.dpool.entity.vo.*;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
@RestController
public class Upload {
@RequestMapping("/upload")
public FileResult upload(@RequestParam("file") MultipartFile picture, HttpServletRequest request) throws FileNotFoundException {
System.out.println("您已进入图片上传服务");
String realPath = ResourceUtils.getURL("classpath:").getPath()+"static/image";
String path = realPath.replace('/', '\\').substring(1,realPath.length());
File filePath = new File(path);
System.out.println("文件的保存路径:" + path);
if (!filePath.exists() && !filePath.isDirectory()) {
System.out.println("目录不存在,创建目录:" + filePath);
filePath.mkdir();
}
String originalFileName = picture.getOriginalFilename();
System.out.println("原始文件名称:" + originalFileName);
String type = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
System.out.println("文件类型:" + type);
String name = originalFileName.substring(0, originalFileName.lastIndexOf("."));
String fileName = UUIDUtils.getUuid() + name + "." + type;
System.out.println("新文件名称:" + fileName);
File targetFile = new File(path, fileName);
System.out.println("图片地址:"+path+"/"+fileName);
try {
picture.transferTo(targetFile);
System.out.println("上传成功");
return new FileResult(true,"http://127.0.0.1:8082/image/"+fileName,path+"/"+fileName);
} catch (IOException e) {
System.out.println("上传失败");
e.printStackTrace();
return new FileResult(false, "上传失败","");
}
}
}
工具类1
package com.example.dpool.entity.vo;
import lombok.Data;
import java.io.Serializable;
@Data
public class FileResult implements Serializable {
private boolean success;
private String message;
private String fileAddress;
private String start;
public FileResult(boolean success, String message,String fileAddress) {
this.success = success;
this.message = message;
this.fileAddress = fileAddress;
}
public boolean isSuccess() {
return success;
}
}
工具类2
package com.example.dpool.entity.vo;
import java.util.UUID;
public class UUIDUtils {
private UUIDUtils(){}
public static String getUuid(){
return UUID.randomUUID().toString().replace("-", "");
}
}