一、如何实现文件上传
*上传*
1.文件上传,创建项目开发
2.创建UploadServlet类主要用于获取表单及其上传文件的信息
3.index.jsp页面的代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
文件上传
二、文件上传的相关API
message.jsp代码:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
上传文件成功
上传文件成功!
UploadServlet代码:
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
public class UploadServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
DiskFileItemFactory sf= new DiskFileItemFactory();//实例化磁盘被文件列表工厂
String path = request.getRealPath("/upload");//得到上传文件的存放目录
sf.setRepository(new File(path));//设置文件存放目录
sf.setSizeThreshold(1024*1024);//设置文件上传小于1M放在内存中
String rename = "";//文件新生成的文件名
String fileName = "";//文件原名称
String name = "";//普通field字段
//从工厂得到servletupload文件上传类
ServletFileUpload sfu = new ServletFileUpload(sf);
try {
List lst = sfu.parseRequest(request);//得到request中所有的元素
for (FileItem fileItem : lst) {
if(fileItem.isFormField()){
if("name".equals(fileItem.getFieldName())){
name = fileItem.getString("UTF-8");
}
}else{
//获得文件名称
fileName = fileItem.getName();
fileName = fileName.substring(fileName.lastIndexOf("\")+1);
String houzhui = fileName.substring(fileName.lastIndexOf("."));
rename = UUID.randomUUID()+houzhui;
fileItem.write(new File(path, rename));
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.sendRedirect("message.jsp");
out.flush();
out.close();
}
}
web的配置文件:
三、实现文件上传
上传页面:
文件上传成功:
四、实现文件下载
前端实现下载代码:
'); $form.attr('action', config.url); for ( var key in config.data) { $form .append(''); } $iframe.append($form); $(document.body).append($iframe); $form[0].submit(); $iframe.remove(); }var excel_param; excel_param = { 'start_time' : $("#start_time").val(), 'end_time' : $("#end_time").val(), 'order_uuids' : order_uuids }; function download() { postDownLoadFile({ url : '/ces/ces.do', data: excel_param, method : 'post' }); $('#excel_modal').modal('hide'); } var postDownLoadFile = function(options) { var config = $.extend(true, { method : 'post' }, options); var $iframe = $(''); var $form = $('
后端的实现代码:
@RestController
@RequestMapping("/file")
public class DownloadController1 {
//业务上需要的参数可以如param1 传递
@RequestMapping(value = "/download")
public Map download(HttpServletRequest request, HttpServletResponse response,String param1,String param2 ) throws Exception {
String realName = "第一节(2).zip"; //文件在浏览器的显示位置
String downLoadPath = ""; //这个参数表示文件在服务器的存储路径
String contentType = "application/octet-stream";
try {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
long fileLength = new File(downLoadPath).length();
response.setContentType(contentType);
response.setHeader("Content-disposition",
"attachment; filename=" + new String(realName.getBytes("utf-8"), "ISO8859-1"));
response.setHeader("Content-Length", String.valueOf(fileLength));
bis = new BufferedInputStream(new FileInputStream(downLoadPath));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
bis.close();
bos.close();
return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "", "");
} catch (Exception e) {
return ResultUtil.put(ConstantUtil.REQUEST_FAIL, "", "");
}
}
}
运行结果:



