文件上传
在以前的学习里有学过文件上传。主要是:
1.使用原始的代码。
2.使用layui里的方法。
在C层的话就是,如下:
protected void doAddPic(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json;charset=utf-8");
// 得到上传文件的part
if(request.getPart("myfile")!=null) {
Part part= request.getPart("myfile");
String name= part.getSubmittedFileName();
// 得到servlet的路径
String path = request.getServletContext().getRealPath("/picture/");
Src src = new Src(path);
List list = new ArrayList();
list.add(src);
picname =name;
// 写到本地路径
part.write(path+ name);
Gson gson = new Gson();
AJGuangchang agj =new AJGuangchang();
agj.setData(list);
agj.setMsg("上传成功");
// 传json参数过去
response.getWriter().print(gson.toJson(agj));
}
}
新的改变
SpringMVC里的主要是在原始代码中进行封装,使代码更简洁和更方便。
1.导入相应的jar主要是
如果没有,可以再链接: https://mvnrepository.com/.下载
2.配置springmvc-servlet.xml文件
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- id一定要有,因为这个bean是先去找id然后在找class的。 -->
<!-- 这个是最大上传文件的大小 -->
<property name="maxUploadSize" value="200000000"></property>
</bean>
需要注意的是bean的id和class一定要写,并且写对,否则或出错。
3.V层的jsp文件
<form action="file" method="post" enctype="multipart/form-data">
<input type="text" id = "gid" name="gid"><br>
<input type="text" id = "gname" name="gname"><br>
<input type="file" id = "myfile" name="myfile"><br>
<input type="submit" id ="" value="提交">
</form>
4.C层的文件
package com.etc.controller;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class FileUpLoad {
@PostMapping("file")
public String upLoad(int gid,String gname,@RequestParam("myfile") MultipartFile file,HttpServletRequest request) {
String path= request.getRealPath("/");
File f = new File(path+file.getOriginalFilename());
System.out.println(path);
try {
file.transferTo(f);
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
return "fail";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "success";
}
}
注意需要这个注解。@RequestParam(“myfile”) MultipartFile file
5.扩展问题
a)多文件上传问题。
思路为:使用一个for循环即可,操作如下:
@PostMapping("files")
public String upLoadfiles(int gid,String gname,@RequestParam("myfile") MultipartFile[] files,HttpServletRequest request) {
for (MultipartFile file : files) {
String path= request.getRealPath("/");
File f = new File(path+file.getOriginalFilename());
System.out.println(path);
try {
file.transferTo(f);
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
return "fail";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return "success";
}
b)文件大小超出范围。
如果超出过大,可能会出现Tomcat自动帮我们重定向。
可以再tomcat的service.xml里配置
<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" maxSwallowSize="-1"/>
<!-- 这里的-1是不限制大小,如果是需要则写一个大小的文件。--!>
需要在springmvc-servlet.xml里配置
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<!-- 遇到问题就会跳转 -->
<prop key="org.springframework.web.multipart.MaxUploadSizeExceededException"></prop>
</props>
</property>
</bean>
c)使用原先的自带的文件上传功能Servlet3+的上传
1.sprigmvc-servlet里添加新的bean
<bean id = "multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver" >
</bean>
2.需要在web.xml里配置开启文件上传。
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<!-- 开启文件上传的配置。 -->
**<multipart-config></multipart-config>**
</servlet>
3.C层。
@PostMapping("afile")
public String addfiles(int gid,String gname,@RequestParam("file") Part file,HttpServletRequest request) {
String path= request.getRealPath("/");
System.out.println(path);
try {
file.write(path+file.getSubmittedFileName());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "fail";
}
return "success";
}
6.文件的下载
@Controller
public class FileDownLoad {
@GetMapping("downfile")
public String downLoad(HttpServletRequest request,HttpServletResponse response,String filename) {
String path= request.getServletContext().getRealPath("/");
System.out.println(path);
File file = new File(path, filename);
//设置强制下载不打开。
response.addHeader("Content-Disposition", "attachment;fileName="+filename);
try {
//
FileInputStream fios = new FileInputStream(file);
byte[] bytes = new byte[fios.available()];
//这里先读出来
fios.read(bytes);
OutputStream os = response.getOutputStream();
//这里在写进去
os.write(bytes);
//关闭流
fios.close();
os.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "success";
}