如何用java从多部分数据格式创建接收代码
我正在尝试使用java将url中的文件作为多部分表单数据发布,并尝试接收存储在特定文件夹中的文件。当我收到一个文件时,它显示空值。因此,我需要如何在java中接收文件。请给出一些有价值的例子,谢谢。我需要在main方法中提供清晰的信息如何用java从多部分数据格式创建接收代码,java,Java,我正在尝试使用java将url中的文件作为多部分表单数据发布,并尝试接收存储在特定文件夹中的文件。当我收到一个文件时,它显示空值。因此,我需要如何在java中接收文件。请给出一些有价值的例子,谢谢。我需要在main方法中提供清晰的信息 package com.jobsonthego.json; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOE
package com.jobsonthego.json;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.FileUtils;
import com.jobsonthego.common.ApplicationAction;
@SuppressWarnings("serial")
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;
// creates a unique boundary based on time stamp
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 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);
System.out.println("bytesRead"+inputStream);
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();
System.out.println("status"+status);
if (status == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println("line"+reader);
response.add(line);
}
reader.close();
httpConn.disconnect();
System.out.println("finish"+response);
} else {
throw new IOException("Server returned non-OK status: " + status);
}
return response;
}
public static void main(String[] args) {
String charset = "UTF-8";
File uploadFile1 = new File("C:/Users/user/Music/22.jpg");
File uploadFile2 = new File("C:/Users/user/Music/22.jpg");
String requestURL = "http://localhost/userinfo/fileUpload";
try {
MultipartUtility multipart = new MultipartUtility(requestURL, charset);
multipart.addHeaderField("User-Agent", "CodeJava");
multipart.addHeaderField("Test-Header", "Header-Value");
multipart.addFilePart("postImage", uploadFile1);
multipart.addFilePart("postImage", uploadFile2);
List<String> response = multipart.finish();
System.out.println("response"+response);
System.out.println("SERVER REPLIED:");
for (String line : response) {
System.out.println(line);
}
} catch (IOException ex) {
System.err.println(ex);
}
}
}
以下代码需要javax.mail依赖项 例如,这是您的主代码
if (mimeMessage.getContentType().contains("multipart")) {
Multipart multiPart = (Multipart) mimeMessage.getContent();
messageContent = (String)messageContent;
messageContent = "";
for (int partCount = 0; partCount < multiPart.getCount(); partCount++) {
MimeBodyPart part = (MimeBodyPart) multiPart
.getBodyPart(partCount);
if (!Part.ATTACHMENT
.equalsIgnoreCase(part.getDisposition())) {
// this part is the message content
content = getText(part,embededImgMap);
}
}
}
使用以下方法获取多部分内容
private String getText(Part p, Map<String, String> embededImgMap) throws MessagingException, IOException {
if(p.isMimeType("image/*")){
InputStream inStream = p.getInputStream();
String contentHeader = p.getHeader("Content-ID")[0];
if(contentHeader !=null){
contentHeader = contentHeader.replaceAll("<", "").replaceAll(">", "");
}
InlineImage inlineImg = new InlineImage();
inlineImg.setCidKey(contentHeader);
inlineImg.setImgData(IOUtils.toByteArray(inStream));
new MessageStoreDAO().storeInlineImg(inlineImg );
embededImgMap.put(contentHeader,p.getFileName());
}
if (p.isMimeType("text/*")) {
String s = "";
Object objContent = p.getContent();
if(objContent instanceof String){
if(p.isMimeType("text/html")){
s = (String) objContent;
}
}else if(objContent instanceof BASE64DecoderStream){
Logger.info("GetBase64 encoding");
}
return s;
}
if (p.isMimeType("multipart/alternative")) {
// prefer html text over plain text
Multipart mp = (Multipart) p.getContent();
String text = null;
for (int i = 0; i < mp.getCount(); i++) {
Part bp = mp.getBodyPart(i);
if (bp.isMimeType("text/plain")) {
String s = getText(bp,embededImgMap);
if (s != null){
return s;
}
} else if (bp.isMimeType("text/html")) {
String s = getText(bp,embededImgMap);
if (s != null){
return s;
}
} else {
return getText(bp,embededImgMap);
}
}
return text;
} else if (p.isMimeType("multipart/*")) {
Multipart mp = (Multipart) p.getContent();
for (int i = 0; i < mp.getCount(); i++) {
String s = getText(mp.getBodyPart(i),embededImgMap);
if (s != null){
return s;
}
}
}else if (p.isMimeType("multipart/related")) {
Multipart mp = (Multipart) p.getContent();
for (int i = 0; i < mp.getCount(); i++) {
String s = getText(mp.getBodyPart(i),embededImgMap);
if (s != null){
return s;
}
}
}
return "";
}