利用HttpClient進行帶參數的http文件上傳


注意:要引用commons-httpclient-3.1.jar

commons-codec.jar

commons-logging.jar這三個包

客戶端例子代碼

import java.io.File;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;

public class Hclient
{
public static void main(String args[])
{
   String targetURL = null;// TODO 指定URL
   File targetFile = null;// TODO 指定上傳文件
  
   targetFile = new File("1.mp3");
   targetURL = "http://localhost:8080/test/uploadFile"; //servleturl
   PostMethod filePost = new PostMethod(targetURL);
  
   try
   {

 
   Part[] parts = { 
    new FilePart(targetFile.getName(), targetFile),
    new StringPart("parm1","parm1Value")
     };
    filePost.setRequestEntity(new MultipartRequestEntity(parts,filePost.getParams()));
    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
    int status = client.executeMethod(filePost);
    if (status == HttpStatus.SC_OK)
    {
     System.out.println("上傳成功");
    }
    else
    {
     System.out.println("上傳失敗");
    }
   }
   catch (Exception ex)
   {
    ex.printStackTrace();
   }
   finally
   {
    filePost.releaseConnection();
   }
}
} 

  服務器端代碼:

@RequestMapping(“/test/uploadFile")
public ModelAndView saveUpload(
@RequestParam("uploadFile") MultipartFile file,
 HttpServletRequest request)
{
        String dir =request.getSession().getServetContext().getRealPath("uploadDir");
        File newPath = new File(dir +"saveFileName.zip");
        file.transferTo(newPath);      
}    

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM