前端使用form表单提交图片后,java后台怎么获取该图片?

 我来答
樊緞上看
2017-10-29
知道答主
回答量:66
采纳率:0%
帮助的人:5.9万
展开全部
上传图片 后台获取的时候直接从数据库拿路径下面这是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后台怎么获取该图片?
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式