@RestController
public class UploadController {
DateTimeFormatter time = DateTimeFormatter. ofPattern ( "yyyy-MM-dd" ) ;
@PostMapping ( "/upload" )
public String upload ( MultipartFile fileUpload, HttpServletRequest request) {
String realPath = request. getSession ( ) . getServletContext ( ) . getRealPath ( "/UploadFie/" ) ;
System. out. println ( realPath) ;
String format = time. format ( LocalDate. now ( ) ) ;
File folder = new File ( realPath + format) ;
System. out. println ( folder) ;
if ( ! folder. isDirectory ( ) ) {
folder. mkdirs ( ) ;
}
System. out. println ( "开始上传" ) ;
String oldName = fileUpload. getOriginalFilename ( ) ;
String newName = UUID. randomUUID ( ) . toString ( ) + oldName. substring ( oldName. lastIndexOf ( "." , oldName. length ( ) ) ) ;
try {
fileUpload. transferTo ( new File ( folder, newName) ) ;
String filePath = request. getScheme ( ) + "://" + request. getServerName ( ) + ":" + request. getServerPort ( ) + "/UploadFile/" + format + newName;
System. out. println ( "上传成功" ) ;
return filePath;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
return "上传失败!" ;
}
}
multipartFile.getOriginalFilename() 空指针异常 页面文件上传name应与 MultipartFile 后的参数值相同 fileUpload request.getSchema()可以返回当前页面使用的协议,http 或是 https; request.getServerName()可以返回当前页面所在的服务器的名字; request.getServerPort()可以返回当前页面所在的服务器使用的端口,就是80; request.getContextPath()可以返回当前页面所在的应用的名字;