Java获取文件地址分隔符:File.separator
java获取项目路径:
new File("").getCanonicalPath();
===================================================================
上传图片代码:
package com.lexue.lexueManager.controller;
import com.lexue.lexueManager.annotation.LoginRequired;
import com.lexue.lexueManager.util.LexueConstant;
import com.lexue.lexueManager.utils.R;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
/**
* @author wyw
* @email 2295929271@qq.com
* @date 2021-10-26 16:20:55
*/
@RestController
@RequestMapping("lexueManager/photo")
public class PhotoController {
@Value("${Photo.domain}")
private String domain;
/**
* 上传图片。
*/
@LoginRequired
@RequestMapping("/upload")
public R uploadPhoto(MultipartFile file) {
if (file == null) {
return R.error("请选择图片上传").put("code", LexueConstant.PHOTO_EMPTY);
}
String fileName = file.getOriginalFilename();//获取初始文件名
int indexOf = fileName.lastIndexOf(".");
if(indexOf == -1){
return R.error("图片格式不正确").put("code", LexueConstant.PHOTO_ERROR);
}
String suffix = fileName.substring(indexOf);//得到文件名后缀 .png等
if(suffix==null||suffix.equals(".")){
return R.error("图片格式不正确").put("code", LexueConstant.PHOTO_ERROR);
}
//BMP、GIF、JPEG、PNG
if(!(suffix.equals(".png")||suffix.equals(".bmp")||suffix.equals(".jpeg")
||suffix.equals(".gif")||suffix.equals(".jpg")||suffix.equals(".PNG")
||suffix.equals(".BMP")||suffix.equals(".JPEG")||suffix.equals(".GIF")
||suffix.equals(".JPG"))){
return R.error("图片格式不正确").put("code", LexueConstant.PHOTO_ERROR);
}
if (StringUtils.isBlank(suffix)) {
return R.error("图片格式不正确-isBlank()").put("code", LexueConstant.PHOTO_ERROR);
}
//判断文件的大小
long size = file.getSize();//这个方法获取得到的是比特,也就是字节
if(size>=1048576*10){
return R.error("图片大小不能超过10M").put("code", LexueConstant.PHOTO_SIZE);
}
// 生成随机文件名
String name = UUID.randomUUID().toString().replaceAll("-", "") + suffix;
//获取当前项目下图片保存的路径
String uploadPath = null;
try {
// c:\\a2295929271\ .....
uploadPath = new File("").getCanonicalPath() + File.separator + "lexue";
} catch (IOException e) {
throw new RuntimeException("获取项目路径失败", e);
}
// 确定文件存放的路径
String ans = uploadPath + File.separator + "file" + File.separator + "photo" + File.separator + name;
File dest = new File(ans);
try {
// 存储文件
file.transferTo(dest);
} catch (IOException e) {
throw new RuntimeException("上传文件失败,服务器发生异常!", e);
}
String result = domain + File.separator + name;
return R.ok().put("code", LexueConstant.SUCCESS).put("url",result);
}
}
postman测试出现错误:
2021-12-06 16:46:50,228 ERROR [http-nio-9000-exec-1] o.a.c.c.C.[.[.[.[dispatcherServlet] [DirectJDKLog.java:175] Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded; nested exception is java.lang.IllegalStateException: org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException: The field file exceeds its maximum permitted size of 1048576 bytes.] with root cause
org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException: The field file exceeds its maximum permitted size of 1048576 bytes.
at org.apache.tomcat.util.http.fileupload.impl.FileItemStreamImpl$1.raiseError(FileItemStreamImpl.java:114)
at org.apache.tomcat.util.http.fileupload.util.LimitedInputStream.checkLimit(LimitedInputStream.java:76)
at org.apache.tomcat.util.http.fileupload.util.LimitedInputStream.read(LimitedInputStream.java:135)
at java.base/java.io.FilterInputStream.read(FilterInputStream.java:106)
at org.apache.tomcat.util.http.fileupload.util.Streams.copy(Streams.java:98)
at org.apache.tomcat.util.http.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:291)
at org.apache.catalina.connector.Request.parseParts(Request.java:2895)
at org.apache.catalina.connector.Request.getParts(Request.java:2797)
at org.apache.catalina.connector.RequestFacade.getParts(RequestFacade.java:1098)
at org.springframework.web.multipart.support.StandardMultipartHttpServletRequest.parseRequest(StandardMultipartHttpServletRequest.java:95)
at org.springframework.web.multipart.support.StandardMultipartHttpServletRequest.<init>(StandardMultipartHttpServletRequest.java:88)
at org.springframework.web.multipart.support.StandardServletMultipartResolver.resolveMultipart(StandardServletMultipartResolver.java:87)
at org.springframework.web.servlet.DispatcherServlet.checkMultipart(DispatcherServlet.java:1178)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1012)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:626)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:888)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1597)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:832)
文件大小不适合。加上配置:
#设置上传文件的大小限制,默认是1M,远远不够用
# spring.servlet.multipart.max-file-size=500MB
# spring.servlet.multipart.max-request-size=500MB
再次测试:
返回的链接作为下次图片获取的连接。直接访问就能得到、。发现似乎连接有错误。
更改代码:
再次访问:
完成!