这种方法是servlet,编写好在web.xml里配置servlet-class和servlet-mapping即可使用
后台(服务端)java服务代码:(上传至ROOT/lqxcPics文件夹下)
package net.htwater.util;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
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 org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import java.io.FileNotFoundException;
@WebServlet(description = "基础数据文件上传并立即处理", urlPatterns = { "/uploadPics" })
public class UploadPics extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Logger log=Logger.getLogger(UploadPics.class.getName());
@SuppressWarnings("rawtypes")
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if (item.isFormField()) {
System.out.println("表单参数名:" + item.getFieldName() + ",表单参数值:" + item.getString("UTF-8"));
} else {
if (item.getName() != null && !item.getName().equals("")) {
System.out.println("上传文件的大小:" + item.getSize());
System.out.println("上传文件的类型:" + item.getContentType());
System.out.println("上传文件的名称:" + item.getName());
String Path = this.getServletContext().getRealPath("");
File tempFile = new File(item.getName());
File file = new File(uploadPath, tempFile.getName());
item.write(file);
request.setAttribute("upload.message", "上传文件成功!");
}else{
request.setAttribute("upload.message", "没有选择上传文件!");
}
}
}
}catch(FileNotFoundException e){
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("upload.message", "上传文件失败!");
}
request.getRequestDispatcher("/uploadResult.jsp").forward(request, response);
}
}
配置web.xml
前端(页面)测试代码:
DEMO下载地址:https://dwz.cn/fgXtRtnu