• java实现Multipart/form-data


    maven

    新的maven和先前的版本的API不同

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpmime</artifactId>
        <version>4.5.3</version>
    </dependency>

    上传

    package uploadTest;
    
    import java.io.File;
    import java.io.IOException;
    import java.nio.charset.Charset;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Set;
    
    import org.apache.http.Consts;
    import org.apache.http.HttpEntity;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.ContentType;
    import org.apache.http.entity.mime.MultipartEntityBuilder;
    import org.apache.http.entity.mime.content.FileBody;
    import org.apache.http.entity.mime.content.StringBody;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.util.EntityUtils;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    public class UploadTest {
        public static Map<String,Object> uploadFileByHTTP(File postFile,String postUrl,Map<String,String> postParam){
            Logger log = LoggerFactory.getLogger(UploadTest.class);
    
            Map<String,Object> resultMap = new HashMap<String,Object>();
            CloseableHttpClient httpClient = HttpClients.createDefault();
            try{
                //把一个普通参数和文件上传给下面这个地址    是一个servlet
                HttpPost httpPost = new HttpPost(postUrl);
                //把文件转换成流对象FileBody
                FileBody fundFileBin = new FileBody(postFile);
                //设置传输参数
                MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
                multipartEntity.addPart(postFile.getName(), fundFileBin);//相当于<input type="file" name="media"/>
                //设计文件以外的参数
                Set<String> keySet = postParam.keySet();
                for (String key : keySet) {
                    //相当于<input type="text" name="name" value=name>
                    multipartEntity.addPart(key, new StringBody(postParam.get(key), ContentType.create("text/plain", Consts.UTF_8)));
                }
    
                HttpEntity reqEntity =  multipartEntity.build();
                httpPost.setEntity(reqEntity);
    
                log.info("发起请求的页面地址 " + httpPost.getRequestLine());
                //发起请求   并返回请求的响应
                CloseableHttpResponse response = httpClient.execute(httpPost);
                try {
                    log.info("----------------------------------------");
                    //打印响应状态
                    //log.info(response.getStatusLine());
                    resultMap.put("statusCode", response.getStatusLine().getStatusCode());
                    //获取响应对象
                    HttpEntity resEntity = response.getEntity();
                    if (resEntity != null) {
                        //打印响应长度
                        log.info("Response content length: " + resEntity.getContentLength());
                        //打印响应内容
                        resultMap.put("data", EntityUtils.toString(resEntity,Charset.forName("UTF-8")));
                    }
                    //销毁
                    EntityUtils.consume(resEntity);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    response.close();
                }
            } catch (ClientProtocolException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            } finally{
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            log.info("uploadFileByHTTP result:"+resultMap);
            return resultMap;
        }
    
        //测试
        public static void main(String args[]) throws Exception {
            //要上传的文件的路径
            String filePath = "d:/test0.jpg";
            String postUrl  = "http://localhost:8080/v1/contract/addContract.do";
            Map<String,String> postParam = new HashMap<String,String>();
            postParam.put("shopId", "15");
            File postFile = new File(filePath);
            Map<String,Object> resultMap = uploadFileByHTTP(postFile,postUrl,postParam);
            System.out.println(resultMap);
        }
    }

    接收

    @Path("addContract.do")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    @Produces(MediaType.TEXT_HTML)
    public String addContract(@Context HttpServletRequest request, @Context HttpServletResponse response){
        try{
            //这里根据业务做修改
            Contract contract = new Contract();
            //重点是调用saveFile方法
            UploadResult uploadResult = saveFile(request);
            contract.setShopId(Integer.valueOf(uploadResult.getParamMap().get("shopId")));
            contract.setContractUrl(uploadResult.getFilePath());
            Boolean success = contractService.addContract(contract);
            return JSON.toJSONString(RespApi.buildResp(200, "success", success));
        } catch (ContractExeption contractExeption) {
            log.warn(ExceptionUtils.getStackTrace(contractExeption));
            return JSON.toJSONString(RespApi.buildResp(400, "fail to add contract", false));
        }
    }
    
    public UploadResult saveFile(HttpServletRequest request) {
        Map<String,String> resultMap = new HashMap<>();
        String fileName = "";
        try {
            if (ServletFileUpload.isMultipartContent(request)) {
                FileItemFactory factory = new DiskFileItemFactory();
            //如果没以下两行设置的话,上传大的 文件 会占用 很多内存,
            //设置暂时存放的 存储室 , 这个存储室,可以和 最终存储文件 的目录不同
            /**
             * 原理 它是先存到 暂时存储室,然后在真正写到 对应目录的硬盘上,
             * 按理来说 当上传一个文件时,其实是上传了两份,第一个是以 .tem 格式的
             * 然后再将其真正写到 对应目录的硬盘上
             */
            //这个tempDir需要自己设置
            File tempF = new File(tempDir);
            if (!tempF.exists()) {
                tempF.mkdirs();
            }
            factory.setRepository(tempF);
            //设置 缓存的大小,当上传文件的容量超过该缓存时,直接放到 暂时存储室
            factory.setSizeThreshold(1024 * 1024);
            //高水平的API文件上传处理
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = null;
            try {
                items = upload.parseRequest(request);
            } catch (FileUploadException e) {
                e.printStackTrace();
            }
            if (items != null) {
                Iterator<FileItem> iter = items.iterator();
                while (iter.hasNext()) {
                    FileItem item = iter.next();
                    //属性字段
                    if (item.isFormField()) {
                        //获取表单的属性名字
                        String name = item.getFieldName();
                        String value = item.getString();
                        resultMap.put(name,value);
                    }
                    //文件
                    if (!item.isFormField() && item.getSize() > 0) {
                     //可以得到流
                     InputStream in = item.getInputStream();
                        fileName = processFileName(item.getName());
                        try {
                            String basePath = getRootPath();
                            String types = "pic";
                            String date = DateUtil.getNowDateStr(DateUtil.TO_DAY);
                            String realPath = basePath + File.separator + types + File.separator + date
                                    + File.separator;
                            //String realPath = basePath + File.separator + types + File.separator + date
                            //        + File.separator;
                            System.out.println(realPath);
                            File file1 = new File(realPath);
                            if (!file1.exists()) {
                                file1.mkdirs();
                            }
                            String name = UUID.randomUUID().toString() + ".jpg";
                            fileName = types + File.separator + date + File.separator + name;
                            File files = new File(realPath + name);
                            item.write(files);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        }
                    }
                }
            }
        } catch (Exception e) {
        }
        UploadResult uploadResult = new UploadResult();
        uploadResult.setFilePath(fileName);
        uploadResult.setParamMap(resultMap);
        return uploadResult;
    }
    
    //返回结果的包装类
    public class UploadResult {
        private String filePath;
        private Map<String,String> paramMap;
    
        public String getFilePath() {
            return filePath;
        }
    
        public void setFilePath(String filePath) {
            this.filePath = filePath;
        }
    
        public Map<String, String> getParamMap() {
            return paramMap;
        }
    
        public void setParamMap(Map<String, String> paramMap) {
            this.paramMap = paramMap;
        }
    }

    参考

    http://lushuifa.iteye.com/blog/2382115

    转载:http://blog.csdn.net/antony9118/article/details/78226426

  • 相关阅读:
    WinCE下SQLCE数据库开发(VS,VB.net,VC++)
    基于VC++的WinCE网口通信
    WinCE下的串口通信开发(VS2005,VB.Net,VC++)
    多线程CSerialPort类的多串口通信实现
    双T滤波电路用于PWM方式DAC的分析
    AD9516锁相环功能外接环路滤波器的设计与分析
    块结构中断有序化处理方法(一种单片机单线程方式下处理多中断的方法)
    STM32F10X固件库函数——串口清状态位函数分析
    STM32和STR71X移植uCos-II操作系统比较分析
    基于uIP和uC/OS-II嵌入式网络开发
  • 原文地址:https://www.cnblogs.com/MuZi0627/p/11598815.html
Copyright © 2020-2023  润新知