在将文件上传到AWS s3存储桶时,其在本地正常工作。但是,当我在tomcat服务器上部署项目时,它给了错误以编写fileoutputstream
((权限被拒绝)
这里是图像
这是我的代码
private File convertMultiPartToFile(MultipartFile file) throws IOException {
File convFile = new File(file.getOriginalFilename());
FileOutputStream fos = new FileOutputStream(convFile);
fos.write(file.getBytes());
fos.close();
return convFile;
}
private String generateFileName(MultipartFile multiPart) {
return new Date().getTime() + "-" + multiPart.getOriginalFilename().replace(" ", "_");
}
private void uploadFileTos3bucket(String fileName, File file) {
s3client.putObject(
new PutObjectRequest(bucketName, fileName, file).withCannedAcl(CannedAccessControlList.PublicRead));
}
并且当我将File更改为Multipartfile
时,显示此错误是我的错误
关于S3,没有问题,因为使用
fileOutputstream而出现此问题,没有指定任何文件夹来写入文件。但是默认情况下,它会将文件写入项目中的target文件夹中。
private File convertMultiPartToFile(MultipartFile file) throws IOException {
File convFile = new File(file.getOriginalFilename());
FileOutputStream fos = new FileOutputStream(convFile);
fos.write(file.getBytes());
fos.close();
return convFile;
}
所以我通过在上传时为server创建了一个folder来解决了代码。下一次请求到达时。我删除现有目录,然后再次创建它,仅用于写入文件。使用下面的代码:tomcat
private File convertMultiPartToFile(MultipartFile file) throws IOException {
deleteDir(new File(NsdlUrlListService.einvoicePath)); //delete a dir
File files = new File("home/ubuntu/txtgenie/einvoice/"); //create a dir
if (!files.exists()) {
if (files.mkdirs()) {
logger.debug("Multiple directories are created!");
} else {
logger.debug("Failed to create multiple directories!");
}
}
File convFile = new File(file.getOriginalFilename());
FileOutputStream fos = new
FileOutputStream("/home/ubuntu/txtgenie/einvoice/"+convFile);
logger.info(" File Name:: {} ", file);
String fileName = null;
byte[] bytes = file.getBytes();
fileName = file.getOriginalFilename();
if (!fileName.equals("No file")) {
try {
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(new File("home/ubuntu/txtgenie/einvoice/"
+ fileName)));
bos.write(bytes);
bos.close();
}
catch (FileNotFoundException fnfe) {
logger.debug("File not found" + fnfe);
}
catch (IOException ioe) {
logger.debug("Error while writing to file" + ioe);
}
}
fos.write(file.getBytes());
fos.close();
return convFile;
}
删除目录
private boolean deleteDir(File file) { logger.debug("DIR to delete :: " +file); if (file.isDirectory()) { String[] children = file.list(); for (int i = 0; i < children.length; i++) { boolean success = deleteDir (new File(file, children[i])); if (!success) { return false; } } } logger.debug("The directory : "+file+" : is deleted."); return file.delete(); }