【1】上传大文件:
前端页面:
1)同步上传:
<html>
<body>
<form action="http://localhost:8081/webProject/api/file/uploadFile" method="post" enctype="multipart/form-data">
<input type="file" name="targetFile" />
<input type="text" name="userName" value="jxn" />
<input type="submit" value="提交" />
</form>
</body>
</html>
2)异步上传:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>异步上传文件</title>
</head>
<body>
<form id= "uploadForm" >
上传文件: <input type="file" name="sendfile"/>
<input type="button" value="上传" onclick="doUpload()" />
</form>
<script src="D:\soft\JQuery\jquery-1.7.2.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
function doUpload() {
// var formData = new FormData($("#uploadForm")[0]);
var formData = new FormData()
formData.append("targetFile",$("#sendfile"));
formData.append("userName","test-username");
$.ajax({
url: 'http://localhost:8081/webProject/api/file/uploadFile' ,
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
dataType:'json',
success: function (data) {
alert(data);
}
});
}
</script>
</body>
</html>
后端:
web.xml
<servlet>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>1 </load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
Spring配置文件:
<jaxrs:server id="restFileService" address="/file">
<jaxrs:providers>
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" />
</jaxrs:providers>
<jaxrs:serviceBeans>
<ref bean="restFileServiceImpl" />
</jaxrs:serviceBeans>
</jaxrs:server>
<bean id="restFileServiceImpl" class="xxx.api.fileprocess.REST.ApiFileProcessServiceImpl" />
接口:
import org.apache.cxf.jaxrs.ext.multipart.Attachment;
import org.apache.cxf.jaxrs.ext.multipart.Multipart;
@Path("")
public interface ApiFileProcessService {
[@POST](https://my.oschina.net/u/210428)
@Path("/uploadFile")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public String uploadFile(@Multipart(value="targetFile")Attachment targetFile, @Multipart(value="userName")String userName);
}
实现:
import org.apache.cxf.jaxrs.ext.multipart.Attachment;
import javax.activation.DataHandler;
public class ApiFileProcessServiceImpl implements ApiFileProcessService {
@Override
public String uploadFile(Attachment targetFile, String userName) {
try {
DataHandler dataHandler = targetFile.getDataHandler();
String originalFileName = new String(dataHandler.getName().getBytes("ISO8859-1"),"UTF-8");
InputStream is = dataHandler.getInputStream();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String saveLocation = "D:\\" + df.format(new Date()) + "_" + originalFileName;
OutputStream out = new FileOutputStream(new File(saveLocation));
int read = 0;
byte[] bytes = new byte[4096];
while ((read = is.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
return "success";
}
}
测试结果:可以轻松处理(上传)1G以上的文件。
【2】上传小文件:
前端页面:
<html>
<body>
<form action="http://localhost:8081/webProject/api/file/uploadCommonFile" method="post" enctype="multipart/form-data">
<input type="file" name="file1" />
<input type="file" name="file2" />
<input type="submit" value="提交" />
</form>
</body>
</html>
后端:
接口:
import javax.ws.rs.core.Context;
@Path("")
public interface ApiFileProcessService {
@POST
@Path("/uploadCommonFile")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public String uploadCommonFile(@Context HttpServletRequest request);
}
实现:
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class ApiFileProcessServiceImpl implements ApiFileProcessService {
@Override
public String uploadCommonFile(HttpServletRequest request) {
try {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload fileUpload = new ServletFileUpload(factory);
List<FileItem> items = fileUpload.parseRequest(request);
for (FileItem item : items) {
if (!item.isFormField()) {
String originalFileName = item.getName();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String saveLocation = "D:\\" + df.format(new Date()) + "_" + originalFileName;
File picFile = new File(saveLocation);
item.write(picFile);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return "success";
}
}
注意:此方法仅适合上传小文件。
【3】下载文件
case1:
接口:
import javax.ws.rs.GET;
import javax.ws.rs.QueryParam;
@Path("")
public interface ApiFileProcessService {
@GET
@Path("/downloadTemplate")
public Response downloadTemplate(@QueryParam("templateName")templateName );
}
实现:
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
public class ApiFileProcessServiceImpl implements ApiFileProcessService {
@Override
public Response downloadTemplate(String templateName) {
File file = null;
String fileName = null;
try {
String applicationPath = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath();
file = new File(applicationPath + "/" + templateName);
fileName = URLEncoder.encode(templateName, "UTF-8"); // 如果不进行编码,则下载下来的文件名称是乱码
} catch (Exception e) {
e.printStackTrace();
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
}
ResponseBuilder response = Response.ok((Object) file);
response.header("Content-Disposition", "attachment; filename=" + fileName);
return response.build();
}
}
case2:
接口:
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
@GET
@Path("/exportTest")
@Produces("application/vnd.ms-excel")
public Response exportTest(@FormParam("str") String str, @Context HttpServletResponse response);
实现:
import javax.ws.rs.core.Response;
import javax.servlet.http.HttpServletResponse;
@Override
public Response exportTest(String str, HttpServletResponse response) {
try {
ServletOutputStream outputStream = response.getOutputStream();
SXSSFWorkbook wb = new SXSSFWorkbook();
wb.setCompressTempFiles(true);
Sheet sheet = wb.createSheet("sheet0");
Row row = sheet.createRow(0);
row.createCell(0).setCellValue("hahaha");
wb.write(outputStream);
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("中文名字.xlsx", "UTF-8"));
response.setContentType("application/vnd.ms-excel");
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}