上传文件时出现400错误。 Chrome开发者日志也只告诉我有400错误。我有一种感觉错误源自我的控制器,但由于它没有发现错误,我很难跟踪错误是否正确。堆栈日志告诉我java.lang.NullPointerException: null
Chrome错误
Object {readyState: 4, responseText: "", status: 400, statusText: "error"}
Stack的错误
null
2017-03-28 08:38:51.322 ERROR 14332 --- [nio-8080-exec-7] g.g.m.a.web.controller.ExamsController : null
java.lang.NullPointerException: null
at gh.gov.moh.admissionsportal.web.controller.ExamsController.uploadFile(ExamsController.java:254) ~[main/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_65]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_65]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_65]
at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_65]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
2017-03-28 08:38:51.353 DEBUG 14332 --- [nio-8080-exec-7] o.s.web.servlet.DispatcherServlet : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
2017-03-28 08:38:51.353 DEBUG 14332 --- [nio-8080-exec-7] o.s.web.servlet.DispatcherServlet : Successfully completed request
上传课程
private BufferedImage cropImageSquare(byte[] image) {
// Get a BufferedImage object from a byte array
BufferedImage croppedImage = null;
try {
InputStream in = new ByteArrayInputStream(image);
BufferedImage originalImage = ImageIO.read(in);
// Get image dimensions
int height = originalImage.getHeight();
int width = originalImage.getWidth();
// The image is already a square
if (height == width) {
return originalImage;
}
// Compute the size of the square
int squareSize = (height > width ? width : height);
// Coordinates of the image's middle
int xc = width / 2;
int yc = height / 2;
// Crop
croppedImage = originalImage.getSubimage(
xc - (squareSize / 2), // x coordinate of the upper-left corner
yc - (squareSize / 2), // y coordinate of the upper-left corner
squareSize, // widht
squareSize // height
);
} catch (IOException e) {
System.out.println(e.getMessage());
} catch (Exception e) {
System.out.println(e.getMessage());
}
return croppedImage;
}
控制器
@PostMapping(value = "/uploadFile")
@ResponseBody
public ResponseEntity<?> uploadFile( MultipartFile uploadfile, Picture picture, Principal principal, MultipartHttpServletRequest request) {
User user = (User) ((UsernamePasswordAuthenticationToken) principal).getPrincipal();
picture.setUser(user);
try {
//Null Error here
MultipartFile multiFile = request.getFile(uploadfile.getOriginalFilename());
System.out.println("File Length:" + multiFile.getBytes().length);
System.out.println("File Type:" + multiFile.getContentType());
// Crop the image (uploadfile is an object of type MultipartFile)
BufferedImage croppedImage = cropImageSquare(multiFile.getBytes());
String fileName=multiFile.getOriginalFilename();
System.out.println("File Name:" +fileName);
String path=request.getServletContext().getRealPath("/");
// Get the filename and build the local file path
File directory= new File(path+ "/uploads");
directory.mkdirs();
String filename = uploadfile.getOriginalFilename();
String ext = FilenameUtils.getExtension(filename);
File outPutFile = new File(directory.getAbsolutePath()+System.getProperty("file.separator")+picture.getUploadfile());
ImageIO.write(croppedImage, ext, outPutFile);
} catch (Exception e) {
System.out.println(e.getMessage());
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
//pictureService.save(picture, uploadfile);
return new ResponseEntity<>(HttpStatus.ACCEPTED);
}
JS FILE
var $formUploader = $("#upload-file-input");
$formUploader.on("submit", function(e){
e.preventDefault();
var data1 = new FormData(this);
$.each($formUploader.serializeArray(), function(i, field) {
data1[field.name] = field.value;
});
//next line will add content of file
data1.append('uploadfile', $('#file')[0].files[0]);
for(var i of data1.entries()){
console.log(i[0] + ' '+ i[1]);
}
$.ajax({
//dataType: 'json',
url: $formUploader.prop('action'),
type: "POST",
data: data1,
enctype: 'multipart/form-data',
processData: false,
contentType: false,
cache: false,
timeout: 10000,
success: function (data) {
console.log(data);
// Handle upload success
$("#upload-file-message").text("File succesfully uploaded");
},
error: function (response) {
console.log(response);
// Handle upload error
$("#upload-file-message").text("File not uploaded (File might be big, size needed.)");
}
});
});
上传表格
<form id="upload-file-input" th:action="@{/uploadFile}" method="post" th:object="${picture}"
enctype="multipart/form-data" class="form-inline inline new-item">
<div th:replace="common/layout :: flash"></div>
<fieldset>
<legend> Upload Picture</legend>
<label class="btn btn-default btn-file">
Browse
<input type="file" id="file" name="uploadfile" onchange="$('#custom-file-control').html($(this).val());"/>
<span id="custom-file-control"></span>
</label>
<span id="upload-file-message"></span>
<button type="submit" class="btn btn-primary">Upload Picture</button>
</fieldset>
<div class="style16"></div>
</form>