如何通过Java中的多部分请求上传大文件?

时间:2014-09-15 14:12:07

标签: java groovy multipart

我正在使用this教程上传大文件,但无法上传300KB的文件。此外,它不会上传*.txt*.log个文件以外的任何内容。需要指针,可以帮助我上传大文件,无论文件类型如何。

分享修改后的代码

public class MultipartUtility {
   private final String boundary
   private static final String LINE_FEED = "\r\n"
   private HttpURLConnection httpConn
   private String charset
   private OutputStream outputStream
   private PrintWriter writer

   public MultipartUtility(String requestURL, String charset)
           throws IOException {
       this.charset = charset

       // creates a unique boundary based on time stamp
       boundary = "===" + System.currentTimeMillis() + "==="        
       URL url = new URL(requestURL)
       httpConn = (HttpURLConnection) url.openConnection()
       httpConn.setUseCaches(false)
       httpConn.setDoOutput(true) // indicates POST method
       httpConn.setDoInput(true)
       httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary)
       httpConn.setRequestProperty("User-Agent", "CodeJava Agent")
       httpConn.setRequestProperty("Test", "Bonjour")
       outputStream = httpConn.getOutputStream()
       writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true)
   }
   public void addFormField(String name, String value) {
       writer.append("--" + boundary).append(LINE_FEED)
       writer.append("Content-Disposition: form-data; name=\"" + name + "\"").append(LINE_FEED)
       writer.append("Content-Type: text/plain; charset=" + charset).append(LINE_FEED)
       writer.append(LINE_FEED)
       writer.append(value).append(LINE_FEED)
       writer.flush()
   }
   public void addFilePart(String fieldName, File uploadFile) throws IOException {
       String fileName = uploadFile.getName()
       writer.append("--" + boundary).append(LINE_FEED)
       writer.append("Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName + "\"").append(LINE_FEED)
       writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(fileName)).append(LINE_FEED)
       writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED)
       writer.append(LINE_FEED)
       writer.flush()

       FileInputStream inputStream = new FileInputStream(uploadFile)
       byte[] buffer = new byte[4096]
       int bytesRead = -1
       while ((bytesRead = inputStream.read(buffer)) != -1) {
           outputStream.write(buffer, 0, bytesRead)
       }
       outputStream.flush()
       inputStream.close()

       writer.append(LINE_FEED)
       writer.flush()
   }
   public void addHeaderField(String name, String value) {
       writer.append(name + ": " + value).append(LINE_FEED)
       writer.flush()
   }
    public List<String> finish() throws IOException {
       List<String> response = new ArrayList<String>()

       writer.append(LINE_FEED).flush()
       writer.append("--" + boundary + "--").append(LINE_FEED)
       writer.close()

       // checks server's status code first
       int status = httpConn.getResponseCode()      //<- Exception coming in this line java.io.IOException: Error writing to server
       if (status == HttpURLConnection.HTTP_OK) {
           BufferedReader reader = new BufferedReader(new InputStreamReader(
                   httpConn.getInputStream()))
           String line = null
           while ((line = reader.readLine()) != null) {
               response.add(line)
           }
           reader.close()
           httpConn.disconnect()
       } else {
           throw new IOException("Server returned non-OK status: " + status)
       }
       return response
   }   
   static main(args) {
       String charset = "UTF-8";
       File uploadFile1 = new File("C:\\1392943434245.xml");
       String requestURL = "http://localhost:10060/testme";

       try {
           MultipartUtility multipart = new MultipartUtility(requestURL, charset);          
           multipart.addFilePart("fileUpload", uploadFile1);
           List<String> response = multipart.finish();          
           println("SERVER REPLIED:");          
           for (String line : response) {
               System.out.println(line);
           }
       } catch (IOException ex) {
           System.err.println(ex);
       }
   }
}

4 个答案:

答案 0 :(得分:0)

尝试此代码,您可以上传任何文件类型

public class TryFile {
public static void main(String[] ar) throws HttpException, IOException, URISyntaxException {
// TODO Auto-generated method stub
TryFile t=new TryFile();
t.method();
}
public void method() throws HttpException, IOException, URISyntaxException 
{
String url="<your url>";
String fileName="<your file name>";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
FileBody fileContent= new FileBody(new File(fileName));

StringBody comment = new StringBody("Filename: " + fileName);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("file", fileContent);
httppost.setEntity(reqEntity);
System.out.println("post length"+reqEntity.getContentLength());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println("end"+resEntity.getContentLength());
}
}

答案 1 :(得分:0)

您是否检查过您的HTTP服务器没有对请求施加大小限制? 是否有足够的内存和磁盘大小? 也许原因不在您的代码中。

答案 2 :(得分:0)

这是用于文件上传的工作代码:

<jsp:useBean id="upBean" scope="session" class="javazoom.upload.UploadBean" >
   <jsp:setProperty name="upBean" property="filesizelimit" value="<%= 1024 * 1024%>" />
</jsp:useBean>

试试这个,

 try {
            if (MultipartFormDataRequest.isMultipartFormData(request)) {
                MultipartFormDataRequest mrequest = new MultipartFormDataRequest(request);
                Hashtable files = mrequest.getFiles();
                byte data[] = null;

                if ((files != null) && (!files.isEmpty())) {
                    fileObj = (UploadFile) files.get("fileUpload");
                    m_imagename = fileObj.getFileName().trim();

                   //File type validator
                    if (!Utility.isValiedFileName1(m_imagename)) {
                        ERROR = "Invalid File Type";
                        response.sendRedirect("XXX.jsp");//response page
                        return;
                    }
                   //file uploader method call
                    if ((fileObj != null) && (fileObj.getFileName() != null)) {
                            data = fileObj.getData();
                            //Java method for uploading 
                            result = imageUpload.copyImage(data);//depCode
                    }
                }
            }
        } catch (Exception e) {
            SystemMessage.getInstance().writeMessage(" ERROR : " + e);
        }

这部分与HTTP相关。

答案 3 :(得分:0)

参考 here

我们可以使用plupload上传任意数量的任意大小的文件。