java httpclient文件上传,springmvc作为服务器端接收文件,以及上传中文件名乱码的解决方法

最近由于项目中需要一个文件上传(基于http)的功能,遇到一些问题,故写此博客防止后面遗忘。

文件上传功能需要一个客户端,一个服务器端,由于客户端不是在前台(jsp,html)触发,而是在java中进行请求,于是采用的org.apache.commons.httpclient.HttpClient 这个类库来进行http post文件操作。服务器端项目是基于SSM(springmvc+spring+mybatis)的,所以接受文件的接口写在一个controller中。
第一步:引入jar包,项目管理采用的maven。
maven pom.xml引入jar包如下:

        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.2.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.0.1</version>
        </dependency>

第二步:需要在springmvc.xml中配置服务器端支持文件上传,添加如下代码:

<!-- 支持上传文件 -->  
   <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" 
   p:maxUploadSize="-1" 
   p:defaultEncoding="UTF-8" ></bean>

第三步:编写服务器端代码:

/**
     * 上传文件test
     * 
     * @return
     * @throws Exception
     * @author amos
     * @date 2017年5月27日 下午3:36:00
     */
    @RequestMapping("/getFileByIo")
    public void getFileByIo(
            @RequestParam(value = "file", required = false) MultipartFile file,
            HttpServletResponse response, HttpServletRequest request)
            throws Exception {
        String fileName = file.getOriginalFilename();
        System.out.println("文件名------>"+fileName+"文件大小"+file.getSize());
        String path="E:/httpServer/"+new Date().getTime()+file.getOriginalFilename();
        file.transferTo(new File(path));
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.write(fileName);
        out.flush();
        out.close();
    }

特殊代码说明: 服务器端采用的springmvc 的MultipartFile 来接受文件,接受到文件之后通过file.transferTo()这个方法将文件移动到本地的文件夹中保存。
需要注意的是@RequestParam(value = “file”, required = false) MultipartFile file 这句中的value=”file”
此处file为服务器端与客户端约定的文件参数名。在下面客户端的代码中会再次提到。

第四步:编写客户端代码:

public String httpUpload(String username, String password, String port,
            String ip, String url_addr, String version, String activeMode,
            File file, int linkTimeout,int dataTimeout) throws IOException {
         PostMethod filePost = new PostMethod("http://"+ip+":"+port+url_addr);
        // filePost.addRequestHeader("Content-Type","text/html;charset=UTF-8");
         HttpClient client = new HttpClient();

         try {
         // 通过以下方法可以模拟页面参数提交
         filePost.setParameter("userName","amos");
         filePost.setParameter("fileName",file.getName());
         Part[] parts = { new CustomFilePart("file", file) };
         filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
         client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
         int status = client.executeMethod(filePost);
         if (status == HttpStatus.SC_OK) {
             //TODO上传成功处理
             System.out.println("上传成功");
         } else {
             //TODO 上传失败处理
             System.out.println("上传失败");
         }

         } catch (Exception ex) {
         ex.printStackTrace();
         } finally {
         filePost.releaseConnection();
         }

         return "success";

    }

特殊代码说明:需要注意的是Part[] parts = { new CustomFilePart(“file”, file) };这句话,这里需要注意两点:
①new CustomFilePart(“file”, file) 第一个”file”,这里是与服务器端约定的文件名参数,参考第三步中有说明,一定要一致。
②此处为什么不直接采用new FilePart(“file” ,file) ,是因为看了FilePart这个类的源码后发现其中有个方法

 protected void sendDispositionHeader(OutputStream out) 
    throws IOException {
        LOG.trace("enter sendDispositionHeader(OutputStream out)");
        super.sendDispositionHeader(out);
        String filename = this.source.getFileName();
        if (filename != null) {
            out.write(FILE_NAME_BYTES);
            out.write(QUOTE_BYTES);
            out.write(EncodingUtil.getAsciiBytes(filename));
            out.write(QUOTE_BYTES);
        }
    }

其中说明了文件名是采用ascii码来传输的,所以无论怎么解析都会出现中文乱码的问题,目前想到的解决方法就是自己写了一个CustomFilePart类来继承FilePart并重写了其中的sendDispositionHeader方法。
CustomFilePart类代码如下:

import java.io.File;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;

import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.util.EncodingUtil;

/**   
*解决中文文件名乱码   
*/    
public class CustomFilePart extends FilePart{

    public CustomFilePart(String name, File file) throws FileNotFoundException {
        super(name, file);
        // TODO Auto-generated constructor stub
    }


     protected void sendDispositionHeader(OutputStream out) throws IOException {     
            super.sendDispositionHeader(out);     
            String filename = getSource().getFileName();     
            if (filename != null) {     
                out.write(EncodingUtil.getAsciiBytes(FILE_NAME));     
                out.write(QUOTE_BYTES);     
                out.write(EncodingUtil.getBytes(filename, "utf-8"));     
                out.write(QUOTE_BYTES);     
            }     
        }     


}

这样便解决了httpClient中文乱码问题。

至此,这边博客就完工了,一个客户端基于java,服务器端基于springmvc的文件传输功能就实现了。感谢读者!希望能够帮到大家!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值