java 图片的上传总结

jsp中上传图片,整理别人的文章,自己测试后又加入了其他方法


需求:前台选择图片,页面显示上传后的图片地址

代码一(方法1): form 提交,获取不了返回值,会刷新页面

<form id="uploadForm" action="http://xxxx/xxx/xx/images/upload?token=tokenstring" method="post" enctype="multipart/form-data">  
   <table>  
       <tr>  
           <td width="100" align="right">图片:</td>  
           <td><input type="file" name="img"/>   <input type="submit" value="Submit"></td>  
       </tr>  
   </table>  
</form> 



代码一(方法2):ajaxUploadImg.jsp,可以有返回值,不刷新页面

百度搜索,并下载jquery.js 及 ajaxfileupload.js

[html]  view plain  copy
 print ?
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%  
  3.     String path = request.getContextPath();  
  4.     String basePath = request.getScheme() + "://"  
  5.             + request.getServerName() + ":" + request.getServerPort()  
  6.             + path + "/";  
  7. %>  
  8.   
  9. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  10. <html>  
  11.   <head>  
  12.     <base href="<%=basePath%>">  
  13.     <meta http-equiv="pragma" content="no-cache">  
  14.     <meta http-equiv="cache-control" content="no-cache">  
  15.     <meta http-equiv="expires" content="0">      
  16.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  17.     <meta http-equiv="description" content="This is my page">  
  18.     <!-- 
  19.     <link rel="stylesheet" type="text/css" href="styles.css"> 
  20.     -->  
  21.     <script language="javascript" src="<%=basePath%>js/jquery.js" ></script>  
  22.     <script language="javascript" src="<%=basePath%>js/ajaxfileupload.js" > </script>   
  23.     <script language="javascript" type="text/javascript" src="<%=basePath%>js/ezeditor.js"></script>  
  24.     <script type="text/javascript">  
  25.     function ajaxFileUpload()  
  26.     {  
  27.       
  28.     $("#loading")  
  29.         .ajaxStart(function(){  
  30.             $(this).show();  
  31.         })//开始上传文件时显示一个图片  
  32.         .ajaxComplete(function(){  
  33.             $(this).hide();  
  34.         });//文件上传完成将图片隐藏起来  
  35.           
  36.        $.ajaxFileUpload({  
  37.                  url:'<%=basePath %>FileUpload',             //需要链接到服务器地址  
  38. //url:'/xxx/xxx/xxx/images/upload.htm?token=tokenstring',//适用于方法一
  39.                  secureuri:false,  
  40.                  fileElementId:'uploadFileInput',                         //文件选择框的id属性  
  41.                  dataType: 'json',                                     //服务器返回的格式,可以是json  
  42.                  success: function (data, status)             //相当于java中try语句块的用法  
  43.                  {     
  44.                  //alert(data);       //data是从服务器返回来的值     
  45.                      $('#result').html('上传图片成功!请复制图片地址<br/>'+data.src);  
  46.    
  47.                  },  
  48.                  error: function (data, status, e)             //相当于java中catch语句块的用法  
  49.                  {  
  50.                      $('#result').html('上传图片失败');  
  51.                  }  
  52.                }  
  53.              );  
  54.     }  
  55.     </script>  
  56.   </head>  
  57.     
  58.   <body>   
  59.   <div id="result" style="FONT:12px 宋体"></div><br/>  
  60.  <img id="loading" src="loading.gif" style="display:none;">  
  61.         <form name="form_uploadImg" action="" method="POST" enctype="multipart/form-data">  
  62.  <input id="uploadFileInput" type="file" size="45" name="uploadFileInput" class="input" />  
  63.  <a href="#" id="buttonUpload" onclick="return ajaxFileUpload();" >上传</a>  
  64. <!-- 上面必须用<a 必须加上href="#" -->
  65.  </form>  
  66. </html>  

代码二(方法1):springMVC

我用的这个方法,方法2 没试

//上传图片的接口
@RequestMapping( value = "/xxxx/images/upload.htm", method = {RequestMethod.POST})
@ResponseBody
public String uploadGoodsCategoryImages(HttpServletRequest req) throws IOException

System.out.println("upload-img---------------");
       //tomcat中文件储存路径,tomcat文件路径
//需要刷新及时刷新,但可以解决,在server.xml中配置:
//<Context docBase="D:\eclipse_workspace\xxxx\WebContent\categoryimages" path="/xxxx/categoryimages" debug="0" reloadable="fasle" privilege="true"/>

String realDir = req.getSession().getServletContext().getRealPath("");  
//tomcat中项目如:C:\apache-tomcat-7.0.70\wtpwebapps\xxxx\
       String filePath = "categoryimages\\";  
       String realPath = realDir+"\\"+filePath;  
       //tomcat中文件路径C:\apache-tomcat-7.0.70\wtpwebapps\xxxx\categoryimages


       DiskFileItemFactory factory = new DiskFileItemFactory();
// 设置文件上传路径
String upload = realPath;
String temp = System.getProperty("java.io.tmpdir");
factory.setSizeThreshold(1024 * 1024 * 5);
factory.setRepository(new File(temp));
ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
       
try
{
List<FileItem> list = servletFileUpload.parseRequest(req);

for (FileItem item : list)
{
String name = item.getFieldName();
InputStream is = item.getInputStream();
try
{
String img_name = comm.buildID20()+".jpg"; //图片名字
inputStream2File(is, upload + img_name);
String img_url = comm.CONTEXTIMGPATH+"/xxx/"+img_name;
return String.format("{\"img_url\":\""+img_url+"\""
+ ",\"status\":\"success\"}");

} catch (Exception e)
{
e.printStackTrace();
}


}

} catch (FileUploadException e)
{
return ”未知错误,请稍后再试“;
}

return String.format(upload);
}



代码二(方法2): FileUpload.java
这里使用了commons-fileupload-1.2.1.jar的包,可以自行搜索下载
如果使用myeclipse,可以直接在Struts 2 Core Libraies中找到.
commons-fileupload-1.2.1.jar


[java]  view plain  copy
 print ?
  1. package com.lz.servlet;  
  2.   
  3. import java.io.BufferedInputStream;  
  4. import java.io.BufferedOutputStream;  
  5. import java.io.File;  
  6. import java.io.FileOutputStream;  
  7. import java.io.IOException;  
  8. import java.util.Date;  
  9. import java.util.regex.Matcher;  
  10. import java.util.regex.Pattern;  
  11.   
  12. import javax.servlet.ServletException;  
  13. import javax.servlet.http.HttpServlet;  
  14. import javax.servlet.http.HttpServletRequest;  
  15. import javax.servlet.http.HttpServletResponse;  
  16.   
  17. import org.apache.commons.fileupload.FileItemIterator;  
  18. import org.apache.commons.fileupload.FileItemStream;  
  19. import org.apache.commons.fileupload.disk.DiskFileItemFactory;  
  20. import org.apache.commons.fileupload.servlet.ServletFileUpload;  
  21. import org.apache.commons.fileupload.util.Streams;  
  22.   
  23. public class FileUpload extends HttpServlet {  
  24.   
  25.     public FileUpload() {  
  26.         super();  
  27.     }  
  28.   
  29.     public void destroy() {  
  30.         super.destroy();   
  31.     }  
  32.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  33.             throws ServletException, IOException {  
  34.   
  35.     }  
  36.   
  37.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  38.             throws ServletException, IOException {  
  39.         response.setContentType("text/html");     
  40.         response.setCharacterEncoding("UTF-8");  
  41.         String realDir = request.getSession().getServletContext().getRealPath("");  
  42.         String contextpath = request.getContextPath();  
  43.         String basePath = request.getScheme() + "://"  
  44.         + request.getServerName() + ":" + request.getServerPort()  
  45.         + contextpath + "/";  
  46.   
  47.         try {  
  48.         String filePath = "uploadfiles";  
  49.         String realPath = realDir+"\\"+filePath;  
  50.         //判断路径是否存在,不存在则创建  
  51.         File dir = new File(realPath);  
  52.         if(!dir.isDirectory())  
  53.             dir.mkdir();  
  54.   
  55.         if(ServletFileUpload.isMultipartContent(request)){  
  56.   
  57.             DiskFileItemFactory dff = new DiskFileItemFactory();  
  58.             dff.setRepository(dir);  
  59.             dff.setSizeThreshold(1024000);  
  60.             ServletFileUpload sfu = new ServletFileUpload(dff);  
  61.             FileItemIterator fii = null;  
  62.             fii = sfu.getItemIterator(request);  
  63.             String title = "";   //图片标题  
  64.             String url = "";    //图片地址  
  65.             String fileName = "";  
  66.             String state="SUCCESS";  
  67.             String realFileName="";  
  68.             while(fii.hasNext()){  
  69.                 FileItemStream fis = fii.next();  
  70.   
  71.                 try{  
  72.                     if(!fis.isFormField() && fis.getName().length()>0){  
  73.                         fileName = fis.getName();  
  74.                         Pattern reg=Pattern.compile("[.]jpg|png|jpeg|gif$");  
  75.                         Matcher matcher=reg.matcher(fileName);  
  76.                         if(!matcher.find()) {  
  77.                             state = "文件类型不允许!";  
  78.                             break;  
  79.                         }  
  80.                         realFileName = new Date().getTime()+fileName.substring(fileName.lastIndexOf("."),fileName.length());  
  81.                         url = realPath+"\\"+realFileName;  
  82.   
  83.                         BufferedInputStream in = new BufferedInputStream(fis.openStream());//获得文件输入流  
  84.                         FileOutputStream a = new FileOutputStream(new File(url));  
  85.                         BufferedOutputStream output = new BufferedOutputStream(a);  
  86.                         Streams.copy(in, output, true);//开始把文件写到你指定的上传文件夹  
  87.                     }else{  
  88.                         String fname = fis.getFieldName();  
  89.   
  90.                         if(fname.indexOf("pictitle")!=-1){  
  91.                             BufferedInputStream in = new BufferedInputStream(fis.openStream());  
  92.                             byte c [] = new byte[10];  
  93.                             int n = 0;  
  94.                             while((n=in.read(c))!=-1){  
  95.                                 title = new String(c,0,n);  
  96.                                 break;  
  97.                             }  
  98.                         }  
  99.                     }  
  100.   
  101.                 }catch(Exception e){  
  102.                     e.printStackTrace();  
  103.                 }  
  104.             }  
  105.             response.setStatus(200);  
  106.             String retxt ="{src:'"+basePath+filePath+"/"+realFileName+"',status:success}";  
  107.             response.getWriter().print(retxt);  
  108.         }  
  109.         }catch(Exception ee) {  
  110.             ee.printStackTrace();  
  111.         }  
  112.           
  113.     }  
  114.     public void init() throws ServletException {  
  115.         // Put your code here  
  116.     }  
  117.   
  118. }  

代码三: web.xml做如下

[html]  view plain  copy
 print ?
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="3.0"   
  3.     xmlns="http://java.sun.com/xml/ns/javaee"   
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
  6.     http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">  
  7.   <display-name></display-name>   
  8.   <welcome-file-list>  
  9.     <welcome-file>index.jsp</welcome-file>  
  10.   </welcome-file-list>  
  11.   
  12.   <servlet>  
  13.     <servlet-name>FileUpload</servlet-name>  
  14.     <servlet-class>com.lz.servlet.FileUpload</servlet-class>  
  15.   </servlet>  
  16.   
  17.   <servlet-mapping>  
  18.     <servlet-name>FileUpload</servlet-name>  
  19.     <url-pattern>/FileUpload</url-pattern>  
  20.   </servlet-mapping>  
  21. </web-app>  
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值