我必须使用servlet在服务器上上传图像,并且对servlet的请求正在通过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);
}
}
}
请帮助如何填写代码以处理请求,如果我能以其他方式执行此操作,请帮助我。
答案 0 :(得分:1)
这是方式:
// Process the uploaded items
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
processFormField(item);
} else {
processUploadedFile(item);
}
}
请参阅: