前言
提示:使用本文的方式进行文件下载需要导入 upload_bill.jar 包,此包在我的资源中已上传。代码很通俗易懂去看看吧。
一、代码如下
package com.hc.servlet;
import com.jspsmart.upload.File;
import com.jspsmart.upload.Files;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/uploadfile")
public class UploadFile extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//创建SmartUpload对象
SmartUpload smartUpload = new SmartUpload();
//初始化
smartUpload.initialize(this.getServletConfig(), req, resp);
try {
smartUpload.upload();
//获取普通表单项值
String txtName1 = smartUpload.getRequest().getParameter("txtName");
System.out.println("txtName:"+txtName1);
Files files = smartUpload.getFiles();
for(int i=0; i<files.getCount(); i++){
//代表一个文件
File file = files.getFile(i);
System.out.println("getFieldName:"+file.getFieldName());
System.out.println("getFileName:"+file.getFileName());
System.out.println("getFileExt:"+file.getFileExt());
System.out.println("getFilePathName:"+file.getFilePathName());
System.out.println("getFileSize:"+file.getSize());
//重新存到指定的路径下
String realPath = req.getSession().getServletContext().getRealPath("uploadfiles/");
realPath = realPath+file.getFileName();
//还需要注意文件重名的情况
//保存文件
file.saveAs(realPath);
}
} catch (SmartUploadException e) {
e.printStackTrace();
}
}
}
springMVC的方式,这里我先在webapp目录下创建了一个upload的目录
@PostMapping("/hello")
public void hello(String username , String password , MultipartFile myFile , HttpServletRequest request) throws IOException {
//打印日志
LOGGER.info("springmvc获取的请求参数是:" + username + "\t" + password + "\t 上传的文件名为:" + myFile.getOriginalFilename());
//保存文件
//改变文件名,避免上传相同的文件名 新文件将原有文件替换
int index = myFile.getOriginalFilename().lastIndexOf(".");
String fileName = myFile.getOriginalFilename().substring(0,index) + System.currentTimeMillis() + new Random().nextInt(1000) + myFile.getOriginalFilename().substring(index);
//获取文件上传的路径
String realPath = request.getServletContext().getRealPath("/upload");
//开始上传
myFile.transferTo(new File(realPath + "/" + fileName));
}