html5 上传图片并浏览

来源:互联网 发布:org.apache.http jar 编辑:程序博客网 时间:2024/05/16 18:40
html: 
<form enctype="multipart/form-data" method="post" action="/my_account/updateUser" >  
<div class="main_mian_div1_div2_div1">
                             <img id="img_id" name="img_id" style="height: 93px; width: 93px;" src="{{users.avatar}}" >
                               <input type="file" id="up_img" name="up_img" style="display: none;" value="" onchange="onLoad(this)" />
<label for="up_img" style="text-align:center; background-color:#e63420;
font-size:12pt;color:#ffffff;border:1px #ff0000 solid;height:30px; width: 93px;
position: absolute; top:63; bottom: 0; right: 0; left: 0;">更改头像</label>
</div>
     <div style="width:100%;height:42px;margin-top:15px;">
       <button style="width:100%;height:42px;margin:0 auto;background-color:#e63420;border- radius:4px;font-size:12pt;color:#ffffff;border:1px #ff0000 solid;" 
                         type="submit" >保存</button>
 </div> 
</form>

js:
 
//修改
var userImgLocal;
userImgLocal=document.getElementById('img_id'); 
$scope.setUpdateUser=function(){
if(isMobile){
if($scope.up_ma==undefined){
 errorMa.innerHTML="请输入验证码!";
 iUser1=false;
}else if($scope.up_ma.length!=4){
 errorMa.innerHTML="输入的验证不符合";
 iUser1=false;
}else if($scope.up_pwd==undefined){
errorPwd.innerHTML="密码不可以为空!";
iUser1=false;
}else if($scope.up_pwd.length<6 || $scope.up_pwd.length>16){
errorPwd.innerHTML="密码长度为(6~16)!"; 
iUser1=false;
}else if($scope.up_pwd2==undefined){
errorPwd2.innerHTML="重复密码不可以为空!";
iUser1=false;
}else if($scope.up_pwd!=$scope.up_pwd2){
  errorPwd2.innerHTML="两次密码不一致";
  iUser1=false;
}else{
iUser1=true;
}
}else{
iUser1=true;
}
   if(!isMobile&&$scope.up_pwd){
   if($scope.up_pwd.length<6 || $scope.up_pwd.length>16){
   errorPwd.innerHTML="密码长度为(6~16)!"; 
   iUser2=false
}else if($scope.up_pwd2==undefined){
errorPwd2.innerHTML="重复密码不可以为空!";
iUser2=false;
}else if($scope.up_pwd!=$scope.up_pwd2){
  errorPwd2.innerHTML="两次密码不一致";
  iUser2=false;
   }else{
   iUser2=true;
   }
}else{
iUser2=true;
}
}

function fileSelect(e) {  
    e = e || window.event;  
       
    var files = e.target.files;  //FileList Objects      
    var ireg = /image\/.*/i,p = document.getElementById('img_id');  
    var ul = document.getElementById('Errors');  
    for(var i = 0, f; f = files[i]; i++) {  
        if(!f.type.match(ireg)) {  
            //设置错误信息  
            var li = document.createElement('li');  
            li.innerHTML = '<li>' + f.name +'不是图片文件.</li>';  
               
            ul.appendChild(li);  
               
            continue;  
        }  
           
        var reader = new FileReader();  
           
        reader.onload = (function(file) {  
            return function(e) {  
//                var span = document.createElement('span');  
//                var img = new Image;  
//                img.alt=file.name;  
//                img.onload = function() {  
//                    console.log(img.height); // image is loaded; sizes are available  
//                };  
//  
//                img.src=this.result;
            userImgLocal.src=this.result;
            userImgLocal.value=file.name;
               // alert(file.name);
               // span.innerHTML = '<img class="thumb" src="'+ this.result +'" alt="'+ file.name +'" />';  
                   
                //p.insertBefore(span, null);  
            };  
        })(f);  
        //读取文件内容  
        reader.readAsDataURL(f);  
    }  
}  
       
if(window.File && window.FileList && window.FileReader && window.Blob) {  
   document.getElementById('up_img').addEventListener('change', fileSelect, false);
} else {  
    document.write('您的浏览器不支持File Api');  
}   
 
java -serlvert:

/*** 
     * 修改用户信息
     * @return 
     */    
@RequestMapping(value="/my_account/updateUser")
@ResponseBody
    public String updateUser(HttpServletRequest request)throws IOException{ 
   Users u=new Users();
   DiskFileItemFactory factory=new DiskFileItemFactory();
        ServletFileUpload sfu=new ServletFileUpload(factory);
        sfu.setHeaderEncoding("UTF-8");  //处理中文问题
        sfu.setSizeMax(1024*1024);   //限制文件大小
   String uMonths="";
   String uDay="";
   InputStream is=null;
        try {
            @SuppressWarnings("unchecked")
List<FileItem> fileItems= sfu.parseRequest(request);  //解码请求 得到所有表单元素
            for (FileItem fi : fileItems) {
                //有可能是 文件,也可能是普通文字 
                if (fi.isFormField()) { 
               
                  if(fi.getFieldName().equals("u_id")){
                 u.setCustomer_id(fi.getString());
                  }else if(fi.getFieldName().equals("up_name")){
                 u.setRealname(fi.getString());
                  }else if(fi.getFieldName().equals("uMonths")){
                 uMonths=fi.getString();
                  }else if(fi.getFieldName().equals("uDay")){
                 uDay=fi.getString();
                   }else if(fi.getFieldName().equals("up_mobile")){
                 u.setMobile(fi.getString());
                   }else if(fi.getFieldName().equals("up_ma")){
                 u.setCode(fi.getString());
                   }else if(fi.getFieldName().equals("up_pwd")){
                 u.setPassword(MD5Utils.MD5(fi.getString()));
                   }
                }else{
                    // 是文件
                    String fn=fi.getName();
                    if(fn.endsWith(".jpg")||fn.endsWith(".png")){
                      u.setPic(fn);
                          is = fi.getInputStream();  
                    }
                   // fi.getFieldName();
                  //  IOUtils.copy(is, output);
                   // Files.copy(is, new File("D:/1.jpg").toPath(), StandardCopyOption.REPLACE_EXISTING);
                   
                    //fi.write(new File("D:/1.jpg"));
//                    if(fn.endsWith(".jpg")||fn.endsWith(".png")){
//                    f=new File(path,fn);
//                    }
                }                
            }    
            
        } catch (Exception e) {
            e.printStackTrace();
        }
   u.setBirth(uMonths+"月"+uDay+"日");
String []param={u.getPic(),
u.getCustomer_id(),
u.getMobile(),
u.getCode(),
u.getRealname(),
u.getBirth(),
u.getPassword(),
MD5Utils.MD5(u.getCustomer_id()+"=jiawang_dd")};

        String url="http://test.diandianwaimai.com:8110/customer/update";
        String str=HttpUtils.sendPost(url,param,is);
        System.out.println(str);
        return null;  
    }  
 处理工具类:
package dd.util;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

import sun.misc.BASE64Decoder;

import com.sun.jersey.core.util.Base64;


/**
 * 链接工具类
 *
 * @author wupengfei
 *
 */
public abstract class HttpUtils {

    private static final Logger LOGGER = Logger.getLogger(HttpUtils.class);

    /**
     * 调用get方法
     *
     * @param url
     * @return
     * @throws IOException
     */
    public static String doGet(String url) throws IOException {
        return doGet(url, "utf-8", "utf-8");
    }

    /**
     * 调用get方法
     *
     * @param url
     * @param requestCharset
     * @param receiveCharset
     * @return
     * @throws IOException
     */
    public static String doGet(String url, String requestCharset, String receiveCharset) throws IOException {
        if (StringUtils.isBlank(url)) {
            return null;
        }
        requestCharset = StringUtils.getDefault(requestCharset, "utf-8");
        receiveCharset = StringUtils.getDefault(receiveCharset, "utf-8");

        String result = null;
        HttpURLConnection connection = null;
        try {
            LOGGER.info("开始调用url=" + url);
            connection = getConnection(url, requestCharset);
            result = getContent(connection.getInputStream(), receiveCharset);
        } catch (Exception e) {
            LOGGER.error("调用url=" + url + "时发生错误", e);
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
        return result;
    }
    /**
     * Post Request
     * @return
     * @throws Exception
     */
    public static String sendPost(String url, String [] params,InputStream is) {
        PrintWriter out = null;
        BufferedReader br = null;
        String result = "";
        try {
            String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
            String CRLF = "\r\n"; // Line separator required by multipart/form-data.
            URLConnection connection = new URL(url).openConnection();
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            connection.connect();
            try {
                OutputStream output = connection.getOutputStream();
                PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, "utf-8"), true);

                // Send normal param.
                writer.append("--" + boundary).append(CRLF);
                writer.append("Content-Disposition: form-data; name=\"customer_id\"").append(CRLF);
                writer.append("Content-Type: text/plain; charset=" + "utf-8").append(CRLF);
                writer.append(CRLF).append(params[1]).append(CRLF).flush();

                // Send normal param.
                writer.append("--" + boundary).append(CRLF);
                writer.append("Content-Disposition: form-data; name=\"mobile\"").append(CRLF);
                writer.append("Content-Type: text/plain; charset=" + "utf-8").append(CRLF);
                writer.append(CRLF).append(params[2]).append(CRLF).flush();

                // Send normal param.
                writer.append("--" + boundary).append(CRLF);
                writer.append("Content-Disposition: form-data; name=\"code\"").append(CRLF);
                writer.append("Content-Type: text/plain; charset=" + "utf-8").append(CRLF);
                writer.append(CRLF).append(params[3]).append(CRLF).flush();

                // Send normal param.
                writer.append("--" + boundary).append(CRLF);
                writer.append("Content-Disposition: form-data; name=\"realname\"").append(CRLF);
                writer.append("Content-Type: text/plain; charset=" + "utf-8").append(CRLF);
                writer.append(CRLF).append(params[4]).append(CRLF).flush();

                // Send normal param.
                writer.append("--" + boundary).append(CRLF);
                writer.append("Content-Disposition: form-data; name=\"birth\"").append(CRLF);
                writer.append("Content-Type: text/plain; charset=" + "utf-8").append(CRLF);
                writer.append(CRLF).append(params[5]).append(CRLF).flush();


                // Send normal param.
                writer.append("--" + boundary).append(CRLF);
                writer.append("Content-Disposition: form-data; name=\"password\"").append(CRLF);
                writer.append("Content-Type: text/plain; charset=" + "utf-8").append(CRLF);
                writer.append(CRLF).append(params[6]).append(CRLF).flush();

                writer.append("--" + boundary).append(CRLF);
                writer.append("Content-Disposition: form-data; name=\"sign\"").append(CRLF);
                writer.append("Content-Type: text/plain; charset=" + "utf-8").append(CRLF);
                writer.append(CRLF).append(params[7]).append(CRLF).flush();

                // Send text file.
                if(null!=is){
                writer.append("--" + boundary).append(CRLF);
         writer.append("Content-Disposition: form-data; name=\"pic\"; filename=\"" +params[0]+ "\"").append(CRLF);
         writer.append("Content-Type: text/plain; charset=" + "utf-8").append(CRLF); // Text file itself must be saved in this charset!
         writer.append(CRLF).flush();
         //Files.copy(f.toPath(), output);
         IOUtils.copy(is, output);
                }
                output.flush(); // Important before continuing with writer!
     writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.
                writer.append("--" + boundary + "--").append(CRLF).flush();
                writer.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

            br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = br.readLine()) != null) {
                result += "\n" + line;
            }
        } catch (Exception e) {
            System.out.println("程序出现异常" + e);
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
    /**
     * 获取连接
     *
     * @param url
     * @param charset
     * @return
     * @throws IOException
     */
    private static HttpURLConnection getConnection(String url, String charset) throws IOException {
        charset = StringUtils.getDefault(charset, "utf-8");

        URL initUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) initUrl.openConnection();
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);

        connection.connect();
        return connection;
    }

    /**
     * 获取流内容,并关闭流
     *
     * @param is
     * @return
     * @throws IOException
     */
    public static String getContent(InputStream is) throws IOException {
        return getContent(is, null);
    }

    /**
     * 获取流内容,并关闭流
     *
     * @param is
     * @param charset
     * @return
     * @throws IOException
     */
    public static String getContent(InputStream is, String charset) throws IOException {
        if (is == null) {
            return null;
        }
        charset = StringUtils.getDefault(charset, "utf-8");

        StringBuffer result =new StringBuffer();
        BufferedReader buffer = null;
        try {
            buffer = new BufferedReader(new InputStreamReader(is, charset));
            String response;
            while ((response = buffer.readLine()) != null) {
                result.append(response);
            }
            return result.toString();
        } finally {
            if(null!=buffer){
                buffer.close();
                buffer=null;
            }
        }
    }

}
0 0