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

下面是一个使用Java实现multipart/form-data接受请求的示例代码: ``` import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.URI; import java.util.List; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; public class MultiPartFormHandler implements HttpHandler { public static void main(String[] args) throws Exception { HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0); server.createContext("/upload", new MultiPartFormHandler()); server.start(); System.out.println("Server started on port 8000"); } @Override public void handle(HttpExchange exchange) throws IOException { String contentType = exchange.getRequestHeaders().getFirst("Content-Type"); if (contentType != null && contentType.startsWith("multipart/form-data")) { InputStream in = exchange.getRequestBody(); MultiPartFormData formData = new MultiPartFormData(in, contentType); List<FormPart> parts = formData.getParts(); for (FormPart part : parts) { if (part.isFile()) { saveFile(part); System.out.println("File saved: " + part.getFileName()); } else { System.out.println(part.getName() + ": " + part.getText()); } } } exchange.sendResponseHeaders(200, 0); exchange.close(); } private void saveFile(FormPart part) throws IOException { File file = new File(part.getFileName()); OutputStream out = new FileOutputStream(file); InputStream in = part.getInputStream(); byte[] buffer = new byte[1024]; int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } out.close(); in.close(); } } class MultiPartFormData { private List<FormPart> parts; public MultiPartFormData(InputStream in, String contentType) throws IOException { String boundary = extractBoundary(contentType); MultipartStream multipartStream = new MultipartStream(in, boundary.getBytes()); boolean nextPart = multipartStream.skipPreamble(); while (nextPart) { String header = multipartStream.readHeaders(); FormPart part = new FormPart(header, multipartStream); parts.add(part); nextPart = multipartStream.readBoundary(); } } private String extractBoundary(String contentType) { String[] elements = contentType.split(";"); for (String element : elements) { element = element.trim(); if (element.startsWith("boundary=")) { return element.substring("boundary=".length()); } } return null; } public List<FormPart> getParts() { return parts; } } class FormPart { private String name; private String fileName; private boolean file; private String text; private InputStream inputStream; public FormPart(String header, InputStream inputStream) throws IOException { String[] elements = header.split(";"); for (String element : elements) { element = element.trim(); if (element.startsWith("name=")) { name = element.substring("name=".length()); } else if (element.startsWith("filename=")) { fileName = element.substring("filename=".length()); file = true; } } if (file) { this.inputStream = inputStream; } else { byte[] buffer = new byte[1024]; int read = inputStream.read(buffer); text = new String(buffer, 0, read); } } public String getName() { return name; } public String getFileName() { return fileName; } public boolean isFile() { return file; } public String getText() { return text; } public InputStream getInputStream() { return inputStream; } } ``` 该示例使用了Java内置的HttpServer和MultipartStream类来处理multipart/form-data请求。HttpServer是一个简单的HTTP服务器,MultipartStream是处理multipart/form-data请求的类。在handle方法中,我们首先检查请求的Content-Type是否是multipart/form-data类型。如果是,我们使用MultipartStream类来解析请求并获取各个部分的内容。对于每个部分,我们检查它是文件还是文本,并执行相应的操作。在这个示例中,我们只是打印文本内容或保存文件。 注意:该示例代码需要Java 8或更高版本才能运行。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值