gpt4 book ai didi

java - 如何使用 jQuery 文件上传和 Spring-boot 解决 java.io.FileNotFoundException

转载 作者:太空宇宙 更新时间:2023-11-04 11:38:28 25 4
gpt4 key购买 nike

我正在尝试上传文件并将文件名保存到数据库中。我已经添加了 CommonsMultipartResolver 依赖项,并在 Spring 配置中定义了 CommonsMultipartResolver bean。已尽我所能,但仍然收到 java.io.FileNotFoundException 错误。

错误

java.io.FileNotFoundException: /private/var/folders/0q/_ll9y13s5rn7cym4_9l6lb0c0000gn/T/tomcat.2486137170479409904.8080/work/Tomcat/localhost/ROOT/upload_2793f497_312d_401f_91e7_d2bc29ddfec6_00000001.tmp (No such file or directory)
at java.io.FileInputStream.open0(Native Method) ~[na:1.8.0_65]
at java.io.FileInputStream.open(FileInputStream.java:195) ~[na:1.8.0_65]
at java.io.FileInputStream.<init>(FileInputStream.java:138) ~[na:1.8.0_65]
at org.apache.tomcat.util.http.fileupload.disk.DiskFileItem.getInputStream(DiskFileItem.java:188) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
at org.apache.catalina.core.ApplicationPart.getInputStream(ApplicationPart.java:100) ~[tomcat-embed-core-8.5.11.jar:8.5.11]
at org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile.getBytes(StandardMultipartHttpServletRequest.java:291) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
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 com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:664) ~[jackson-databind-2.8.7.jar:2.8.7]
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:690) ~[jackson-databind-2.8.7.jar:2.8.7]
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155) ~[jackson-databind-2.8.7.jar:2.8.7]
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:704) ~[jackson-databind-2.8.7.jar:2.8.7]
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:690) ~[jackson-databind-2.8.7.jar:2.8.7]
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155) ~[jackson-databind-2.8.7.jar:2.8.7]
at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:149) ~[jackson-databind-2.8.7.jar:2.8.7]
at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serialize(CollectionSerializer.java:112) ~[jackson-databind-2.8.7.jar:2.8.7]

配置

 @Bean
public MultipartResolver multipartResolver()
{
return new StandardServletMultipartResolver();
}

@Bean
public MultipartResolver multipartResolver2() {
return new CommonsMultipartResolver();
}

Controller

@PostMapping(value = "/uploadFile")
@ResponseBody
public ResponseEntity<Object> uploadFile(@RequestParam("uploadfile") MultipartFile uploadfile, Picture picture, Principal principal) {
User user = (User) ((UsernamePasswordAuthenticationToken) principal).getPrincipal();
picture.setUser(user);
try {
// Crop the image (uploadfile is an object of type MultipartFile)
BufferedImage croppedImage = cropImageSquare(uploadfile.getBytes());

// Get the filename and build the local file path
String filename = uploadfile.getOriginalFilename();
String directory = "/Users/molayodecker/Sites/admissionsPortal/data";
String filepath = Paths.get(directory, filename).toString();
String ext = FilenameUtils.getExtension(filename);

// Save the file locally
File outPutFile = new File(filepath);
ImageIO.write(croppedImage, ext, outPutFile);
//stream.write(uploadfile.getBytes());
} catch (Exception e) {
System.out.println(e.getMessage());
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
pictureService.save(picture, uploadfile);
return new ResponseEntity<>(HttpStatus.ACCEPTED);
} // method uploadFile

表格

<form  id="upload-file-input" th:action="@{/uploadFile}" method="post" th:object="${picture}" 
enctype="multipart/form-data" class="form-inline inline new-item">
<input type="file" id="file" name="uploadfile" />
<span class="placeholder" data-placeholder="Choose an image...">Choose an image...</span>
<label for="file" class="button">Browse</label>
<button type="submit" class="btn btn-primary">Upload</button>
</form>

JS 文件

var $formUploader = $("#upload-file-input");
$formUploader.on("submit", function(e){
e.preventDefault();
//var data = new FormData(this);
var data={};
$.each($(this).serializeArray(), function(i, field){
data[field.name] = field.value;
});
$.ajax({
//dataType: 'json',
url: $formUploader.prop('action'),
type: "POST",
//data: new FormData($("#upload-file-input")[0]),
data: data,
enctype: 'multipart/form-data',
processData: false,
contentType: false,
cache: false,
success: function (data) {
// Handle upload success
$("#upload-file-message").text("File succesfully uploaded");
},
error: function () {
// Handle upload error
$("#upload-file-message").text("File not uploaded (File might be big, size needed.)");
}
});
});

最佳答案

我认为您的 Spring 应用程序中的 CSRF 保护已启用。你应该添加 _csrf_header ,_csrf 与你的ajax请求例如:

var header = $("meta[name='_csrf_header']").attr("content");
var token = $("meta[name='_csrf']").attr("content");
$.ajax({
url: '/test',
type: 'POST',
beforeSend: function(xhr){
xhr.setRequestHeader(header, token);
},
success: function(data) {
-----
}
}

您还可以禁用 csrf _csrf_header ->

@Configuration
public class App extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
}
}

关于java - 如何使用 jQuery 文件上传和 Spring-boot 解决 java.io.FileNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43032458/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com