前端使用form表单提交图片后,java后台怎么获取该图片?
展开全部
上传图片 后台获取的时候直接从数据库拿路径下面这是servlet的内容:吵高package demo;import java.io.File;import java.io.IOException;import java.io.PrintWriter;import java.util.List;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.ProgressListener;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;public class DemoServlet extends HttpServlet {private static final String UPLOAD_DIRECTORY = "upload";private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MBprivate static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MBprivate static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MBprotected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {DiskFileItemFactory factory=new DiskFileItemFactory();ServletFileUpload sfu=new ServletFileUpload(factory);sfu.setHeaderEncoding("UTF-8");sfu.setProgressListener(new ProgressListener() {public void update(long pBytesRead, long pContentLength, int pItems) {System.out.println("文件大小为:"+pContentLength+",当前已处理:升穗尺"+pBytesRead);}});//判断提交上来的数据是否是上传表单的数据if(!ServletFileUpload.isMultipartContent(request)){PrintWriter writer= response.getWriter();writer.println("Error:表单必须包含 enctype=multipart/form-data");writer.flush();return;}factory.setSizeThreshold(MEMORY_THRESHOLD);//设置临时储存目录factory.setRepository(new File(System.getProperty("java.io.tmpdir")));//设置最大文件上传值sfu.setFileSizeMax(MAX_FILE_SIZE);//设置最族铅大请求值(包含文件和表单数据)sfu.setSizeMax(MAX_REQUEST_SIZE);String uploadpath=getServletContext().getRealPath("./")+ File.separator+UPLOAD_DIRECTORY;File file=new File(uploadpath);if(!file.exists()){file.mkdir();}try {List formItems = sfu.parseRequest(request);if(formItems!=null&&formItems.size()>0){for(FileItem item:formItems){if(!item.isFormField()){String fileName=new File(item.getName()).getName();String filePath=uploadpath+File.separator+fileName;File storeFile=new File(filePath);System.out.println(filePath);item.write(storeFile);request.setAttribute("message", "文件上传成功!");}}}} catch (Exception e) {request.setAttribute("message", "错误信息:"+e.getMessage());}getServletContext().getRequestDispatcher("/demo.jsp").forward(request, response);}}下面是jsp的内容,jsp放到webapp下,如果想放到WEB-INF下就把servlet里转发的路径改一下:Insert title here前端使用form表单提交图片后,java后台怎么获取该图片?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询