采用的是zyupload小插件 点击下载源代码
先给大家看下效果
创建web项目后到导入必须的jar包,(SSM项目框架有之前的案例,需要的去我前边的帖子下载)
其中这俩个jar包很关键、
commons-fileupload-1.2.2.jar
commons-io-1.3.2.jar
控制层代码
package com.jsx.controller;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
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;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.fasterxml.jackson.annotation.JsonTypeInfo.None;
@Controller
public class UploadController {
//上传文件的保存路径
protected String configPath = "upload";
//上传文件的临时保存路径
protected String dirTemp = "upload/temp";
//上传文件的临时文件名
protected String dirName = "file";
//文件上传
@RequestMapping(value = "/upload/Upload") //访问的路径
public void upload(HttpServletRequest request, HttpServletResponse response) throws IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
//文件保存目录路径
// String savePath = "E:/";
String savePath = request.getServletContext().getRealPath("/") + configPath;
// 临时文件目录
String tempPath = request.getServletContext().getRealPath("/") + dirTemp;
//上传时间的具体文件夹-----------------可选--------------------------
// SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
// String ymd = sdf.format(new Date());
// savePath += "/" + ymd + "/";
//上传时间的临时文件夹-----------------可选--------------------------
//tempPath += "/" + ymd + "/";
//创建存放文件夹-----------------------------------
File dirFile = new File(savePath);
if (!dirFile.exists()) {
dirFile.mkdirs();
}
//创建临时文件夹 ---------------------------------
File dirTempFile = new File(tempPath);
if (!dirTempFile.exists()) {
dirTempFile.mkdirs();
}
//------------------------上传优化--------------------------------
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(20 * 1024 * 1024); //设定使用内存超过5M时,将产生临时文件并存储于临时目录中。
factory.setRepository(new File(tempPath)); //设定存储临时文件的目录。
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
try {
List items = upload.parseRequest(request);
System.out.println("items = " + items);
Iterator itr = items.iterator();
while (itr.hasNext())
{
FileItem item = (FileItem) itr.next();
String fileName = item.getName();
long fileSize = item.getSize();
if (!item.isFormField()) {
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
try{
File uploadedFile = new File(savePath, newFileName); //保存路径 文件名
OutputStream os = new FileOutputStream(uploadedFile);
InputStream is = item.getInputStream();
byte buf[] = new byte[1024];//可以修改 1024 以提高读取速度
int length = 0;
while( (length = is.read(buf)) > 0 ){
os.write(buf, 0, length);
}
//关闭流
os.flush();
os.close();
is.close();
System.out.println("上传成功!路径:"+savePath+"/"+newFileName); //后台打印路径
out.print(savePath+"/"+newFileName); //前台打印路径
out.print(" <a href='download.action?filename="+newFileName+"'>文件下载</a> ");
}catch(Exception e){
e.printStackTrace();
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
out.flush();
out.close();
}
@RequestMapping("download")
public ResponseEntity<byte[]> download(@RequestParam("filename") String filename,Model moder,HttpServletRequest request) throws IOException{
String path = request.getServletContext().getRealPath("/upload/"); //得到服务器图片文件夹真实路径
File file=new File(path+File.separator+filename);//拼装新路径
HttpHeaders headers = new HttpHeaders();//设置头
String downName = new String(filename.getBytes("UTF-8"),"ISO-8859-1"); //解决文件名中文乱码问题
headers.setContentDispositionFormData("attachment", downName);//通知浏览器以attachment(下载方式)打开文件
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);//MediaType.APPLICATION_OCTET_STREAM设置为二进制流数据
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers,HttpStatus.CREATED);//201状态,下载文件是新创建,所以create
}
}
jsp页面与样式省略