Pārlūkot izejas kodu

因账号权限问题,上传文件时写入失败,不再修改上传的临时路径为根路径,更改创建文件的方式

sunyj 9 gadi atpakaļ
vecāks
revīzija
e2a2d11f1d

+ 0 - 22
src/main/java/com/uas/report/WebAppConfiguration.java

@@ -1,15 +1,11 @@
 package com.uas.report;
 
-import java.io.File;
 import java.nio.charset.Charset;
 import java.util.Arrays;
 import java.util.List;
 
-import javax.servlet.MultipartConfigElement;
-
 import org.apache.axis.transport.http.AxisServlet;
 import org.springframework.boot.web.servlet.FilterRegistrationBean;
-import org.springframework.boot.web.servlet.MultipartConfigFactory;
 import org.springframework.boot.web.servlet.ServletRegistrationBean;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.ComponentScan;
@@ -111,22 +107,4 @@ public class WebAppConfiguration extends WebMvcConfigurerAdapter {
 		return servletRegistrationBean;
 	}
 
-	/**
-	 * 设置文件上传临时路径
-	 * 
-	 * @return
-	 */
-	@Bean
-	public MultipartConfigElement multipartConfigElement() {
-		MultipartConfigFactory multipartConfigFactory = new MultipartConfigFactory();
-		File file = new File(System.getProperty("java.io.tmpdir"));
-		// 获取磁盘根路径
-		while (file != null && file.getParent() != null) {
-			file = file.getParentFile();
-		}
-		// 设置为根路径(避免使用默认的临时路径,造成文件上传失败)
-		multipartConfigFactory.setLocation(file.getPath());
-		return multipartConfigFactory.createMultipartConfig();
-	}
-
 }

+ 9 - 4
src/main/java/com/uas/report/service/impl/FileServiceImpl.java

@@ -155,9 +155,9 @@ public class FileServiceImpl implements FileService {
 			targetFile.getParentFile().mkdirs();
 		}
 		try {
-			file.transferTo(targetFile);
+			FileUtils.create(targetFile.getAbsolutePath(), file.getBytes());
 			return "成功上传文件至:" + targetFile.getPath();
-		} catch (IllegalStateException | IOException e) {
+		} catch (IllegalStateException | IOException | ReportException e) {
 			e.printStackTrace();
 			return "文件上传失败: " + fileName;
 		}
@@ -179,9 +179,14 @@ public class FileServiceImpl implements FileService {
 		for (MultipartFile file : files) {
 			targetFile = new File(targetFile.getParent() + "/" + file.getOriginalFilename());
 			try {
-				file.transferTo(targetFile);
+				// 不能使用file.transferTo(targetFile),
+				// 因为在spring boot下上传文件时会对临时路径进行处理,
+				// 导致最终文件路径不正确,如果手动设置临时路径为根路径,
+				// 又会因为权限问题导致文件写入失败,
+				// 所以自己在指定路径创建文件,而不使用transferTo方法
+				FileUtils.create(targetFile.getAbsolutePath(), file.getBytes());
 				stringBuilder.append("成功上传文件至:");
-			} catch (IllegalStateException | IOException e) {
+			} catch (IllegalStateException | IOException | ReportException e) {
 				e.printStackTrace();
 				stringBuilder.append("上传文件失败:");
 			}