<!--文件上传的jar包-->
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<!--配置文件解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="#{10240000}"></property>
<property name="defaultEncoding" value="utf-8"></property>
</bean>
注:multipartResolver,如下图源码,这是默认的;
<form action="/upload" method="post" enctype="multipart/form-data">
用户文件:<input type="file" name="filename"><br/>
用户名: <input type="text" name="username"><br/>
<input type="submit" value="提交">
</form>
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.schema.Model;
import java.io.File;
import java.io.IOException;
@Controller
public class FileUploadController {
@ResponseBody
@RequestMapping(value = "/upload",method = RequestMethod.POST)
public String upload(@RequestParam(value = "username",required = false)String username,
@RequestParam("filename") MultipartFile multipartFile, Model model){
System.out.println("username:"+username);
//这是页面上的文件字段的字段名
System.out.println("finename:"+multipartFile.getName());
//文件的名字
System.out.println("finename:"+multipartFile.getOriginalFilename());
try {
//保存文件
multipartFile.transferTo(new File("F:\\"+multipartFile.getOriginalFilename()));
System.out.println("end");
} catch (IOException e) {
e.printStackTrace();
}
return "文件上传成功!";
}
}
@ResponseBody
@RequestMapping(value = "/uploads",method = RequestMethod.POST)
public String uploads(@RequestParam(value = "username",required = false)String username,
@RequestParam("filename")MultipartFile[] multipartFiles, Model model){
System.out.println("username:"+username);
try {
for(MultipartFile file:multipartFiles){
//保存文件
file.transferTo(new File("F:\\haha\\"+file.getOriginalFilename()));
}
System.out.println("end");
} catch (IOException e) {
e.printStackTrace();
}
return "文件上传成功!";
}
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
package com.wkl;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
/**
* @author wkl
* @create 2022-06-24 19:02
*/
@Controller
@RequestMapping("/test")
public class testController {
@RequestMapping(value = "/exportFile", method = RequestMethod.GET)
public ResponseEntity<byte[]> exportActivityForSearch(HttpServletRequest httpRequest) {
//得到请求路径
String contextPath = httpRequest.getContextPath();
//找到系统的根路径
ServletContext servletContext = httpRequest.getServletContext();
//得到文件的真实路径-也可以从系统中获取
String realPath = servletContext.getRealPath("/WEB-INF/dispatcher-servlet.xml");
System.out.println("上边可以从系统中获取绝对路径:"+realPath);
//拿到文件流
InputStream fileInputStream = null;
ResponseEntity<byte[]> stringResponseEntity = null;
try {
fileInputStream = new FileInputStream("E:\\DevelopAPI\\Jquery\\jquery1.7_20120209.xlsx");
byte[] tmp = new byte[fileInputStream.available()];
fileInputStream.read(tmp);
//设置请求头,制定文件类型和文件名称
String fileName = "导出_"+System.currentTimeMillis();
MultiValueMap headers = new HttpHeaders();
headers.add("Content-disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1") + ".xlsx");
stringResponseEntity = new ResponseEntity<byte[]>(tmp, headers, HttpStatus.OK);
} catch (FileNotFoundException e) {
//打印异常日志
} catch (IOException e) {
//打印异常日志
}finally {
try {
fileInputStream.close();
} catch (IOException e) {
//打印异常日志
}
}
return stringResponseEntity;
}
}
jersey框架是什么,请看这篇文章:Jersey框架和springmvc框架
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
<version>2.25</version>
</dependency>
在web.xml中注册:只需要在Jersey的ServletContainer中添加initparam即可:
<init-param>
<param-name>jersey.config.server.provider.classnames</param-name>
<param-value>org.glassfish.jersey.media.multipart.MultiPartFeature</param-value>
</init-param>
@POST
@Path("image1")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
public String upload(@FormDataParam("file") InputStream fileInputStream,
@FormDataParam("file") FormDataContentDisposition disposition, @Context ServletContext ctx) {
File upload = new File(ctx.getRealPath("/upload"),
UUID.randomUUID().toString() + "." + FilenameUtils.getExtension(disposition.getFileName()));
try {
FileUtils.copyInputStreamToFile(fileInputStream, upload);
} catch (IOException e) {
e.printStackTrace();
}
return "success";
}
简单解释一下这段代码:
1,请求必须是POST的,这个不用多说;
2,请求返回json格式响应;
3,Consumes这次设置的是MediaType.MULTIPART_FORM_DATA,这个很重要,因为要能够上传,需要要求表单的提交格式为multipart/form-data;
4,重点在于资源方法的参数,在这里,我们使用了@FormDataParam(该标签来源于jersey的multipart包),该标签能够在资源方法上绑定请求编码类型为multipart/form-data中的每一个实体项
@POST
@Path("image2")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
public String upload2(@FormDataParam("file") FormDataBodyPart bp, @Context ServletContext ctx) {
File upload = new File(ctx.getRealPath("/upload"), UUID.randomUUID().toString() + "."
+ FilenameUtils.getExtension(bp.getFormDataContentDisposition().getFileName()));
try {
FileUtils.copyInputStreamToFile(bp.getValueAs(InputStream.class), upload);
} catch (IOException e) {
e.printStackTrace();
}
return "success";
}
<!--aapache的导入导出文件工具类-->
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<!--返回响应的Respose-->
<!-- https://mvnrepository.com/artifact/javax.ws.rs/javax.ws.rs-api -->
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.1.1</version>
</dependency>
————————————————
版权声明:本文为CSDN博主「苍煜」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_41694906/article/details/107200144
package com.wkl;
import com.alibaba.fastjson.JSONObject;
import com.engine.core.impl.Service;
import javax.ws.rs.core.Response;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Map;
/**
* @author wkl
* @create 2022-06-24 19:36
*/
@Path("/downloaddetail")
public class DownloadController {
@GET
@Path("/downloadDetail")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response downloadDetail(@Context HttpServletRequest request){
InputStream in = null;
ByteArrayOutputStream bos = null;
try {
String fileName = "";
String contentType = "";
String substring = fileName.substring(fileName.lastIndexOf("."));
JSONObject contype = this.getContype();
in = new FileInputStream("E:\\DevelopAPI\\Jquery\\jquery1.7_20120209.xlsx");
bos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while((len = in.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
return Response.ok(bos.toByteArray())
.header("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"))
.header("Cache-Control", "no-cache")
.header("content-type", contentType ).build();
}catch (Exception e){
bs.writeLog(this.getClass().getName()+"------DoccumentImpl : downUpload Exception---"+e.getMessage(),e);
}finally {
try {
if(in != null) {
in.close();
}
if(bos != null) {
bos.close();
}
}catch (IOException e){
bs.writeLog(this.getClass().getName()+"------DoccumentImpl : downUpload Exception---"+e.getMessage(),e);
}
}
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}