[前后端分离]java:图片与缩略图上传(不使用FTP)

上传图片保存至tomcat下的webapps/upload/picture文件夹中:

protected String[] upload(HttpServletRequest request) throws IOException {

String filePaths="";

String thumbnailPaths="";

String path = request.getSession().getServletContext().getRealPath("/");

String basePath =  "../ webapps/upload/picture ";; //文件存放路径

 String urlPath=""; //访问图片路径 

//创建一个通用的多部分解析器 

CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext()); 

//判断 request 是否有文件上传,即多部分请求 

int imgNum = 0;    //图片数量

if(multipartResolver.isMultipart(request)){ //转换成多部分request

MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request; //取得request中的所有文件名

Iterator iter = multiRequest.getFileNames();

int k=1;

while(iter.hasNext()){

List multipartFiles = multiRequest.getFiles(iter.next());

for (MultipartFile multipartFile : multipartFiles) {

if(ArrayUtils.contains(contentTypes,multipartFile.getContentType())){    // contentTypes为图片格式

/*String[] contentTypes= {"image/gif","image/x-icon","image/jpeg","application/x-png","image/png","application/x-jpg","application/x-bmp"}*/

String fileName = multipartFile.getOriginalFilename();

if (StringUtils.isNotEmpty(fileName)) {

imgNum++;

fileName=fileName.substring(fileName.lastIndexOf("."));

long mills=System.currentTimeMillis();

int randomNum=(int)(Math.random()*100000);

int num=k++; String filePath= mills +"_img_" + randomNum + "_" + num + fileName; filePaths += urlPath + filePath + "|"; multipartFile.transferTo(new File(basePath + filePath));    // transferTo 将 图片 输出到路径下

String thumbnailPath= mills + "_thumbnail_" + randomNum + "_" + num + fileName;

Thumbnails.of(basePath + filePath) .size(380, 380)    //缩小图片为380*380大小

.toFile(basePath + thumbnailPath);        // transferTo 将图片输出到路径下

thumbnailPaths += urlPath + thumbnailPath + "|"; }

} } } } 

filePaths=filePaths.length()>1?filePaths.substring(0,filePaths.length()-1):filePaths; 

thumbnailPaths=thumbnailPaths.length()>1?thumbnailPaths.substring(0,thumbnailPaths.length()-1):thumbnailPaths; 

return new String[]{filePaths,thumbnailPaths,String.valueOf(imgNum)}; }       

你可能感兴趣的:([前后端分离]java:图片与缩略图上传(不使用FTP))