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;
    }
}
版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

uploadfile上传图片

配合ASP.NET 2.0提供了FileUpload控件,很容易就可以完成文件上传功能。做了一个简单的上传逻辑,实现了:检查了文件是否存在、自动生成文件名、自动建立上传文件夹、对文件类型作校验等功能。...

FineUploader文件/图片和form表单参数一起上传,从入门到精通教程

这里推荐两篇博客供入门 点击打开链接  FineUploader+struts2+手动点击提交,若报缺少id="qq-template"的错,可以参照我下文更改。 点击打开链接  FineUploa...

uploadFile+nginx实现上传图片(Windows/Linux均可用)

上传图片的功能想必并不是什么费劲的事儿了,但大多数童鞋都是在本机(也是tomcat/jboss服务器)实现上传,且没有考虑图片重命名(中文乱码)的问题。        这篇博客的上传图片是基于真实的项...

推荐Huploadify实现上传图片或文件

之前项目用uploadify(flash version)实现图片上传功能,依赖于flash的上传插件浏览器兼容性不够,于是找了Huploadify替代uploadify,原因如下: 1、不依赖于fl...

利用开源组件commons-fileupload上传图片文件(2)

上一篇文章讲解了比较基础的文件上传,

Delphi7高级应用开发随书源码

  • 2003年04月30日 00:00
  • 676KB
  • 下载

前台上传文件以及页面的文件显示操作

1、UI布局: (1)添加图片位的div:             (2)文件显示的模板布局(重点):...
  • DHASA
  • DHASA
  • 2016年03月10日 13:13
  • 2774

JS 实现上传照片到服务器 和 后台处理处理这个照片

前端通过js实现获取用户上传的照片,然后传到服务器上,后台又java实现

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

httpPost发送带上传图片的完整代码

调用图片上传http接口,利用httpClient模拟请求

上传图片除了上传到本地服务器之外,通常需要上传到 public static JSONObject postImg(String url, File savedDir, String saveFi...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:HttpUploadFile模拟前台POST上传图片和后台获取上传图片并上传至服务器
举报原因:
原因补充:

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