springMVC图片上传

xiaoxiao2021-02-28  121

1:springMVC里的上传配置:

<!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 默认编码 --> <property name="defaultEncoding" value="utf-8" /> <!-- 文件大小最大值 --> <property name="maxUploadSize" value="10485760000" /> <!-- 内存中的最大值 --> <property name="maxInMemorySize" value="40960" /> <!-- 为上传文件的临时路径 <property name="uploadTempDir" value="fileUpload/temp" ></property> --> </bean>

2:文件上传的流程:

2.1:先删除以前的旧有文件(原文件存在的话);

2.2:判断存储文件的文件夹是否存在,不存在的话,先创建,避免 报错。

2.3:再上传新有文件。

3:上传思路:

考虑到文件的上传原理,就是对数据流的操作。拿到传到后台控制器中的输入流InputStream,再用文件输出流FileOutputStream来输出保存到服务器。

4:部分代码:

import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import com.alibaba.fastjson.JSONObject; @Controller @RequestMapping("/upload") public class FilesUploadController { /*** * 上传文件 用@RequestParam注解来指定表单上的file为MultipartFile * 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。 * @param file * @return */ @ResponseBody @RequestMapping(value="/fileUpload") public JSONObject fileUpload(HttpServletRequest request,@RequestParam("file") MultipartFile file ,@RequestParam("deleteImg") String deleteImg) { String filePaths = request.getSession().getServletContext().getRealPath("/"); int num = filePaths.indexOf("name");//name项目名称 String filePath =filePaths.substring(0, num); File fileDirectory =new File(filePath+"static/upload/"); //如果文件夹不存在则创建 if (!fileDirectory .exists()) { fileDirectory .mkdirs(); } if(backImg!=null && !"".equals(backImg)){ new File(filePath+"static/upload/"+deleteImg).delete(); } String suffixName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));// 获得上传文件的后缀名 String fileName=UUID.randomUUID().toString().replace("-", "")+suffixName; // 判断文件是否为空 if (!file.isEmpty()) { filePath=filePath+"static/upload/"+fileName; InputStream in = null; //Output to file FileOutputStream outputStream=null; try { in = file.getInputStream(); outputStream=new FileOutputStream(new File(filePath)); //一次读多个字节 byte[] tempbytes = new byte[1024]; int byteread = 0; //读入多个字节到字节数组中,byteread为一次读入的字节数 while ((byteread = in.read(tempbytes)) != -1){ outputStream.write(tempbytes, 0, byteread); outputStream.flush(); } } catch (Exception e1) { e1.printStackTrace(); } finally { if (in != null){ try { in.close(); } catch (IOException e1) { } } if (outputStream != null){ try { outputStream.close(); } catch (IOException e1) { } } } } JSONObject responseJsonObject = new JSONObject(); responseJsonObject.put("ok", "上传成功"); responseJsonObject.put("fileName", fileName); return responseJsonObject; } /*** * 保存文件 * @param file * @return */ private boolean saveFile(HttpServletRequest request,MultipartFile file) { // 判断文件是否为空 if (!file.isEmpty()) { // 文件保存路径 String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/" + file.getOriginalFilename(); try { // 转存文件 file.transferTo(new File(filePath)); return true; } catch (FileNotFoundException e) { new File(filePath).mkdirs(); try { file.transferTo(new File(filePath)); return true; } catch (IllegalStateException | IOException e1) { e1.printStackTrace(); } } catch (IllegalStateException | IOException e) { e.printStackTrace(); } } return false; } /*** * 多文件上传 * @param file * @return */ @RequestMapping("/filesUpload") public String filesUpload(HttpServletRequest request,@RequestParam("files") MultipartFile[] files) { //判断file数组不能为空并且长度大于0 if(files!=null&&files.length>0){ //循环获取file数组中得文件 for(int i = 0;i<files.length;i++){ MultipartFile file = files[i]; //保存文件 saveFile(request,file); } } // 重定向 return "redirect:/competition/showCompetition"; } }

5:代码还可以再处理下,便于通用。首先关于“/”的处理,可以通过JDK提供的接口来替换,便于在不同的系统下使用。

int num = filePaths.indexOf("name");//name项目名称

name可以通过代码来动态获取项目名称,不建议代码中写死。

转载请注明原文地址: https://www.6miu.com/read-35355.html

最新回复(0)