文件上传API因angularjs发布调用而失败。以下是文件上传API代码,
FileUploadController.java
@RestController
@RequestMapping(value="/v1")
public class FileUploadController {
@Autowired
private ServletContext context;
@RequestMapping(value = "/fileUpload", headers = "content-type=multipart/*", method = RequestMethod.POST)
public ResponseEntity<FileInfo> upload(@RequestParam("file") MultipartFile inputFile){
FileInfo fileInfo = new FileInfo();
HttpHeaders headers = new HttpHeaders();
if(!inputFile.isEmpty()){
try {
String originalFileName = inputFile.getOriginalFilename();
File destinationFile = new File(context.getRealPath("/WEB-INF/images") + File.separator + originalFileName);
inputFile.transferTo(destinationFile);
fileInfo.setFileName(destinationFile.getPath());
fileInfo.setFileSize(inputFile.getSize());
headers.add("FileUploaded Successfully - ", originalFileName);
return new ResponseEntity<FileInfo>(fileInfo, headers, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<FileInfo>(HttpStatus.BAD_REQUEST);
}
}
return new ResponseEntity<FileInfo>(HttpStatus.BAD_REQUEST);
}
}
SimpleCorsFilter.java
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
public class SimpleCorsFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with, X-Auth-Token, Content-Type");
response.setHeader("Access-Control-Allow-Credentials","false");
chain.doFilter(req, res);
}
}
堆栈跟踪:
SEVERE [http-nio-8080-exec-9] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [appServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request; nested exception is org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found] with root cause
Angularjs测试代码:
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
}]);
myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
$scope.uploadFile = function(){
var file = $scope.myFile;
console.log('file is ' );
console.dir(file);
var uploadUrl = "http://xxx/v1/fileUpload";
//var uploadUrl = "http://localhost:8080/xxx/v1/fileUpload";
fileUpload.uploadFileToUrl(file, uploadUrl);
};
}]);
问题:
所请求的资源上没有“ Access-Control-Allow-Origin”标头。因此,不允许访问源'http://localhost'。响应的HTTP状态码为500。
请帮助我纠正此问题
最佳答案
在控制器方法上使用@CrossOrigin
查看示例:https://spring.io/guides/gs/rest-service-cors/
@CrossOrigin(origins = "*")
@RequestMapping(value = "/fileUpload", headers = "content-type=multipart/*", method = RequestMethod.POST)
public ResponseEntity<FileInfo> upload(@RequestParam("file") MultipartFile inputFile){
关于java - 所请求的资源上存在“Access-Control-Allow-Origin” header 导致的 Spring 文件上传失败,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45524570/