1:javaWeb原生api上传下载(了解一下就行,平时不用)
原生javaweb文件上传下载链接
2:SpringMVC的上传下载
1:上传-利用fileupload进行上传
1:导包
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
2:配置文件上传解析器
<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,如下图源码,这是默认的;
3:文件上传页面
<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>
4:文件上传处理器
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 "文件上传成功!";
}
}
5:多文件上传
@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 "文件上传成功!";
}
2:下载-利用springmvc的ResponseEntity<byte[]>下载文件
1:导入原生api包,方便使用原生HttpServletRequest
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
2:利用文件流获取文件并封装到ResponseEntity
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;
@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;
}
}
3:jersey框架上传下载
jersey框架是什么,请看这篇文章:Jersey框架和springmvc框架
1:jersey框架上传
1:导包-maven中添加multipart的依赖:
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
<version>2.25</version>
</dependency>
2:配置-需要在Jersey中引入MultipartFeature。MultiPartFeature是Jersey中针对Multipart的一种特征。
在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>
3:第一种方式我们采用的是直接使用InputStream来提供上传文件的输入流;
@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中的每一个实体项
4:第二种方式,我们使用较为底层的FormDataBodyPart来完成。综合两种方式,更建议使用第一种方式来完成文件上传
@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";
}
2:jersey框架下载
1:导包-导入原生的javax包
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<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
2:利用Respose来返回文件流
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;
@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();
}
}
|