TZ_06_SpringMVC_传统文件上传和SpringMVC文件上传方式

时间:2022-03-07 18:40:33

1.传统文件上传方式

<!-- 文件上传需要的jar -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>

  1>form.jsp配置

  设置编码方式为:多部分表格-数据

<form action="fileUpload" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="upload"><br>
<input type="submit" value="传统方式">
</form>

   2>uploadController

/**
* 传统模式的文件上传
*
* @param model
* @return
* @throws Exception
*/
@RequestMapping("/fileUpload")
public String testFileUpload(HttpServletRequest request) throws Exception { String path = request.getSession().getServletContext().getRealPath("/upload");
File file = new File(path);
System.out.println("path:" + path);
if (!file.exists()) {
file.mkdir();
} // 解析request对象,获取上传文件项
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(request);
// 获得enctype="multpart/form-data"的表单项 for (FileItem item : items) {
if (item.isFormField()) {
} else {
// 获取上传文件想项
String fileName = item.getName();
                String name = UUID.randomUUID().toString().replace("-", "")+fileName;
         item.write(new File(file, name));
// 在内存中删除临时文件
item.delete();
}
}
return "success";
}

2.SpringMVC文件上传

  1>form.jsp配置

  设置编码方式为:多部分表格-数据

<form action="fileUpload2" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="upload"><br> //name必须时controller就收的参数名
<input type="submit" value="SpringMVC方式">
</form>

  2>配置上传文件的文件解析器

<!--配置上传文件的文件解析器 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10485760"></property>
</bean>

  3>uploadController

public class UserController {

    /**
* Springmvc模式的文件上传
*
* @param model
* @return
* @throws Exception
*/
@RequestMapping("/fileUpload2")
public String testFileUpload2(MultipartFile upload, HttpServletRequest request) throws Exception { String path = request.getSession().getServletContext().getRealPath("/upload");
File file = new File(path);
System.out.println("path:" + path);
if (!file.exists()) {
file.mkdir();
} // 获取上传文件想项
 String name = UUID.randomUUID().toString().replace("-", "")+upload.getOriginalFilename();
upload.transferTo(new File(path, name));
return "success";
}

                                                           

                                                          ————你是我自罚三杯也不肯开口的秘密