gpt4 book ai didi

java - 由servlet处理的多部分图像上传post请求

转载 作者:行者123 更新时间:2023-12-01 15:14:51 24 4
gpt4 key购买 nike

我必须使用 servlet 在服务器上上传图像,并且对 servlet 的请求正在通过 post 方法。post请求的代码如下:

public class PostImageRequest {
public static void main(String[] args) throws Exception {

final String exsistingFileName = "E:\\Users\\snikhil\\Downloads\\qwe.jpg";
File binaryFile = new File(exsistingFileName);
String param = "value";
DataInputStream inStream = null;
String boundary = Long.toHexString(System.currentTimeMillis()); // JustRandomValue

String CRLF = "\r\n"; // Line separator required by multipart/form-data.
String charset = "UTF-8";
String urlString = "http://localhost:89/ImageUploaderv3/ImageUploadServlet";

URLConnection connection = new URL(urlString).openConnection();
connection.setDoOutput(true);// it is to indicate post method call
connection.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
PrintWriter writer = null;

try {
OutputStream output = connection.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(output, charset),
true); // true = autoFlush, important!

// Send normal param.
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"param\"")
.append(CRLF);
writer.append("Content-Type: text/plain; charset=" + charset)
.append(CRLF);
writer.append(CRLF);
writer.append(param).append(CRLF).flush();

// Send binary file.
writer.append("--" + boundary).append(CRLF);
writer.append(
"Content-Disposition: form-data; name=\"binaryFile\"; filename=\""
+ binaryFile.getName() + "\"").append(CRLF);
writer.append(
"Content-Type: "
+ URLConnection.guessContentTypeFromName(binaryFile
.getName())).append(CRLF);
writer.append("Content-Transfer-Encoding: binary").append(CRLF);
writer.append(CRLF).flush();
InputStream input = null;
try {
input = new FileInputStream(binaryFile);
byte[] buffer = new byte[1024];
for (int length = 0; (length = input.read(buffer)) > 0;) {
output.write(buffer, 0, length);
}
output.flush(); // Important! Output cannot be closed. Close of
// writer will close output as well.
} finally {
if (input != null)
try {
input.close();
} catch (IOException logOrIgnore) {
}
}
writer.append(CRLF).flush(); // CRLF is important! It indicates end
// of binary boundary.
// End of multipart/form-data.
writer.append("--" + boundary + "--").append(CRLF);
} finally {
if (writer != null)
writer.close();
}
// ------------------ read the SERVER RESPONSE

try {
inStream = new DataInputStream(connection.getInputStream());
String str;
while ((str = inStream.readLine()) != null) {
System.out.println("Server response is: " + str);
System.out.println("");
}
inStream.close();

} catch (IOException ioex) {
System.out.println("From (ServerResponse): " + ioex);

}

}

}

现在我正在尝试使用 commons-fileupload-1.2.2 和 commons-io-2.4 jar 在服务器上上传图像,但我不知道如何处理该请求。在这种情况下如何使用 FileItem 的迭代器?servlet部分的代码如下。

class ImageUploadServlet extends HttpServlet {

private boolean isMultipart;
private String filePath;
private int maxFileSize = 50 * 1024;
private int maxMemSize = 4 * 1024;
private File file;
private String realpath;

public void init() {
// Get the file location where it would be stored.
filePath = getServletContext().getInitParameter("file-upload");
String h;
h = getInitParameter("realpath");
if (h != null) {
realpath = h;
}
realpath = getServletConfig().getServletContext().getRealPath(realpath) + "/";
System.err.println("realparh is is =" + realpath);
}

//call post method
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {

isMultipart = ServletFileUpload.isMultipartContent(request);
isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
if (!isMultipart) {
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>No file uploaded</p>");
out.println("</body>");
out.println("</html>");
return;
}

DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("F:\\Servers\\temp"));

// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax(maxFileSize);

try {
List<FileItem> fileItems = upload.parseRequest(request);
///how to process request here ...
///Image file send .....



} catch (Exception ex) {
System.out.println(ex);
}



}

}

请帮助如何填写代码来处理请求,如果我可以通过其他方式做到这一点,请帮助我。

最佳答案

就是这样:

// Process the uploaded items

Iterator iter = items.iterator();

while (iter.hasNext()) {

FileItem item = (FileItem) iter.next();

if (item.isFormField()) {

processFormField(item);
} else {

processUploadedFile(item);
}
}

参见:

关于java - 由servlet处理的多部分图像上传post请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11772142/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com