HttpUploadFile模拟前台POST上传图片和后台获取上传图片并上传至服务器

原创 2016年12月26日 14:59:06
package dshui;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.activation.MimetypesFileTypeMap;

/**
 * HttpUploadFile模拟POST上传图片
 * 
 * @author Administrator
 *
 */
public class HttpUploadFile {

    public static void main(String[] args) {
        testUploadImage();
    }

    /**
     * 测试上传图片
     */
    public static void testUploadImage() {
        String url = "http://127.0.0.1/uploadImage.do";
        String fileName = "C:/Users/Administrator/Desktop/image/1.jpg";
        Map<String, String> textMap = new HashMap<String, String>();// 上传内容
        // 可以设置多个input的name,value
        textMap.put("name", "testname");
        textMap.put("type", "2");
        // 设置file的name,路径
        Map<String, String> fileMap = new HashMap<String, String>();// 上传图片
        fileMap.put("upfile", fileName);
        String contentType = "";// 上传类型,可为空
        String ret = formUpload(url, textMap, fileMap, contentType);
        System.out.println(ret);
    }

    /**
     * 上传图片
     * 
     * @param urlStr
     *            上传地址
     * @param textMap
     *            文本集
     * @param fileMap
     *            图片集
     * @param contentType
     *            没有传入文件类型默认采用application/octet-stream
     *            contentType非空采用filename匹配默认的图片类型
     * @return 返回response数据
     */
    @SuppressWarnings("rawtypes")
    public static String formUpload(String urlStr, Map<String, String> textMap, Map<String, String> fileMap,
            String contentType) {
        String res = "";
        HttpURLConnection conn = null;
        // boundary就是request头和上传文件内容的分隔符
        String BOUNDARY = "---------------------------123821742118716";
        try {
            URL url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(30000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
            OutputStream out = new DataOutputStream(conn.getOutputStream());
            // text
            if (textMap != null) {
                StringBuffer strBuf = new StringBuffer();
                Iterator iter = textMap.entrySet().iterator();
                while (iter.hasNext()) {
                    Map.Entry entry = (Map.Entry) iter.next();
                    String inputName = (String) entry.getKey();
                    String inputValue = (String) entry.getValue();
                    if (inputValue == null) {
                        continue;
                    }
                    strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
                    strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n");
                    strBuf.append(inputValue);
                }
                out.write(strBuf.toString().getBytes());
            }
            // file
            if (fileMap != null) {
                Iterator iter = fileMap.entrySet().iterator();
                while (iter.hasNext()) {
                    Map.Entry entry = (Map.Entry) iter.next();
                    String inputName = (String) entry.getKey();
                    String inputValue = (String) entry.getValue();
                    if (inputValue == null) {
                        continue;
                    }
                    File file = new File(inputValue);
                    String filename = file.getName();

                    // 没有传入文件类型,同时根据文件获取不到类型,默认采用application/octet-stream
                    contentType = new MimetypesFileTypeMap().getContentType(file);
                    // contentType非空采用filename匹配默认的图片类型
                    if (!"".equals(contentType)) {
                        if (filename.endsWith(".png")) {
                            contentType = "image/png";
                        } else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg")
                                || filename.endsWith(".jpe")) {
                            contentType = "image/jpeg";
                        } else if (filename.endsWith(".gif")) {
                            contentType = "image/gif";
                        } else if (filename.endsWith(".ico")) {
                            contentType = "image/image/x-icon";
                        }
                    }
                    if (contentType == null || "".equals(contentType)) {
                        contentType = "application/octet-stream";
                    }
                    StringBuffer strBuf = new StringBuffer();
                    strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
                    strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + filename
                            + "\"\r\n");
                    strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
                    out.write(strBuf.toString().getBytes());
                    DataInputStream in = new DataInputStream(new FileInputStream(file));
                    int bytes = 0;
                    byte[] bufferOut = new byte[1024];
                    while ((bytes = in.read(bufferOut)) != -1) {
                        out.write(bufferOut, 0, bytes);
                    }
                    in.close();
                }
            }
            byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
            out.write(endData);
            out.flush();
            out.close();
            // 读取返回数据
            StringBuffer strBuf = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                strBuf.append(line).append("\n");
            }
            res = strBuf.toString();
            reader.close();
            reader = null;
        } catch (Exception e) {
            System.out.println("发送POST请求出错。" + urlStr);
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
        }
        return res;
    }
}

package com.iit.core.util;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.dshui.oms.entity.Picture;
import com.iit.core.AppConfig;
import com.iit.core.Constants;
import com.iit.core.Convert;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

public class UploadImage extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public static String getFilePath() {
        return "file/" + Convert.toShortYMDWithNoSplit(new Date()) + "/";
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

    private void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        ServletOutputStream os = response.getOutputStream();

        /*
        *    oos需要的属性
        * */

         String endpoint = "http://oss-cn-beijing.aliyuncs.com";
         String accessKeyId = "ytkBktFF0pPFRKh2";
         String accessKeySecret = "EHOxUevFMBIxv6qBaVCT9pOcybZykt";
         String bucketName = "goods-images";
        OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);


        System.out.println(ServletFileUpload.isMultipartContent(request));


        // 获得文件保存路径
    /*  String filePath = getFilePath();
        String path = getTempPath(filePath);
        */

        // 临时文件目录
      File temp = new File("/usr/local/temp/upload/");
        if (!temp.exists())
            temp.mkdirs();

        // 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload
        DiskFileItemFactory factory = new DiskFileItemFactory(5 * 1024 * 1024, temp);
        // 用以上工厂实例化上传组件
        ServletFileUpload sfu = new ServletFileUpload(factory);
        // 单个文件最大值
        sfu.setSizeMax(5* 1024 * 1024);

        List fileList = null;
        try {
            fileList = sfu.parseRequest(request);
        } catch (FileUploadException e) {
            if (e instanceof SizeLimitExceededException) {
                os.write("文件太大了".getBytes("UTF-8"));
                os.close();
                return;
            } else {
                os.write("未知异常".getBytes("UTF-8"));
                os.close();
                return;
            }
        }

        if (fileList == null || fileList.size() == 0) {
            os.write("请上传文件".getBytes("UTF-8"));
            os.close();
            return;
        }

        String fileNames = null;
        Iterator iter = fileList.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (!item.isFormField()) {
                String fileName = item.getName();
                if(fileName.lastIndexOf('.') == -1){
                    return;
                }
                String fileExt = fileName.substring(fileName.lastIndexOf('.'));
                if (!Picture.ALLOW_EXT.contains(fileExt.toLowerCase())) {
                    os.write("文件类型错误".getBytes("UTF-8"));
                    os.close();
                    return;
                }
                fileName = getFileName() + fileExt;
                try {
                   // 这里将图片上传到oos服务器上面服务器上面
                    File file = File.createTempFile(fileName, fileExt);
                    file.deleteOnExit();
                    item.write(file);
                    client.putObject(new PutObjectRequest(bucketName, fileName,file));
                    file.delete();


                    //item.write(new File(path, fileName));
                } catch (OSSException oe) {
                    System.out.println("Caught an OSSException, which means your request made it to OSS, "
                            + "but was rejected with an error response for some reason.");
                    System.out.println("Error Message: " + oe.getErrorCode());
                    System.out.println("Error Code:       " + oe.getErrorCode());
                    System.out.println("Request ID:      " + oe.getRequestId());
                    System.out.println("Host ID:           " + oe.getHostId());
                } catch (ClientException ce) {
                    System.out.println("Caught an ClientException, which means the client encountered "
                            + "a serious internal problem while trying to communicate with OSS, "
                            + "such as not being able to access the network.");
                    System.out.println("Error Message: " + ce.getMessage());
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                } finally {
                    client.shutdown();
                }

                if (fileNames == null)
                    fileNames = fileName;
                else
                    fileNames += "," + fileName;
            }
        }
        os.write((Constants.SUCCESS + "|" + fileNames).getBytes("UTF-8"));
        os.close();
        return;
    }

    public static String getTempPath(String filePath) {
        String projectName = AppConfig.PROJECT_NAME;
        String ret = AppConfig.getResourceHome();
        String contextPath = AppConfig.getContextPath();
        if (!contextPath.equals(projectName) && ret.contains(projectName)) {
            ret = ret.substring(0, ret.indexOf(projectName) - 1);
        }
        String path = ret + AppConfig.RESOURCE_APP_ROOT + filePath;
        // 文件上传目录
        File sourceFile = new File(path);
        if (!sourceFile.exists()) {
            sourceFile.mkdirs();
        }
        return path;
    }

    /**
     * 获取文件名
     * UUID 拼接 8位日期
     *
     * 如需获得原图,可将图片名称截后六位即图片创建日期,然后到file文件夹下根据日期即可找到
     * @return
     */
    public static String getFileName(){
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String time = Convert.toShortYMDWithNoSplit(new Date());
        return uuid + time;
    }
}
版权声明:本文为博主原创文章,未经博主允许不得转载。

安卓上传图片实例,multipart/form-data实现安卓上传文件的功能

一、http协议中普通的Post请求 一般HTTP请求格式为: 请求行(request-line),用来说明请求类型,要访问的资源以及所使用的HTTP版本. 首部(header)小节,用来说...
  • u010335298
  • u010335298
  • 2016年07月08日 17:54
  • 15768

post上传图片到服务器

这几天,项目需要将图片,音频文件(如mp3)上传到服务器,以方便之后的使用。在网上查询了很多资料,一般有以下几种方式,1.ASIHTTPRequest 方式 2. AFNetWorking方式,3....
  • cancan8538
  • cancan8538
  • 2014年11月04日 17:37
  • 6984

使用form-data表单上传图片

这是参考的大神的文章,链接忘了,这是很早的参考文章写出来的。只需改动几个地方,就OK public class FileImageUpload {private static final Strin...
  • hello_xiaozhou
  • hello_xiaozhou
  • 2016年06月23日 14:32
  • 2886

微信公众号开发_HttpUploadFile的代码(五)

package com.igoxin.weixin.custom; import java.io.BufferedReader; import java.io.DataInputStream; im...
  • qq_24784495
  • qq_24784495
  • 2016年10月10日 18:29
  • 489

http upload image demo

  • 2015年02月04日 16:34
  • 1.4MB
  • 下载

HttpClient通过Post上传文件

在之前一段的项目中,使用Java模仿Http Post方式发送参数以及文件,单纯的传递参数或者文件可以使用URLConnection进行相应的处理。           但是项目中涉及到既要传递...
  • jdsjlzx
  • jdsjlzx
  • 2013年04月19日 19:28
  • 82662

使用HttpClient发送HttpPost请求包含上传本地图片和远程图片的传输实现

httpPost发送带上传图片的完整代码
  • kioo_i_see
  • kioo_i_see
  • 2017年10月13日 14:54
  • 1085

如何使用http或httpClient向服务器上传图片 以及使用http上传图片时协议的描述

向服务器上传图片的实例:   在java web中上传图片相对比较容易,只需简单几个按钮和应用即可,以下的例子是如何使用http或httpClient向本地服务器上传图片。 1.网页版    在本...
  • u011572517
  • u011572517
  • 2016年01月09日 19:51
  • 5086

上传文件过大的问题FileUploadBase$SizeLimitExceededException

FileUploadBase$SizeLimitExceededException: the request was rejected because its size ..exc 在上传94M...
  • chenmeng2192089
  • chenmeng2192089
  • 2012年11月12日 20:15
  • 10835

org.apache.commons.fileupload.FileUploadBase$SizeLimitExceededException:

今天在做数据导入时遇到这个异常(使用spring),文件大小受限,需要在配置文件中将文件限制放大,配置如下: 如果struts2中遇到改异常也需要修改配置文件:constant na...
  • tianqiqing2012
  • tianqiqing2012
  • 2016年04月07日 15:54
  • 188
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:HttpUploadFile模拟前台POST上传图片和后台获取上传图片并上传至服务器
举报原因:
原因补充:

(最多只允许输入30个字)