gpt4 book ai didi

java - 使用Java代码创建文件上传请求

转载 作者:行者123 更新时间:2023-11-29 21:38:30 24 4
gpt4 key购买 nike

我想在 android 中实现一个聊天应用程序。在我的应用程序中,我想在服务器上上传一个文件,所以我使用这段代码在服务器端监听文件请求。

 protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");
// Create path components to save the file
final String path = "/home/vibhor/vibhor";
final Part filePart = request.getPart("file");
final String fileName = getFileName(filePart);
OutputStream out = null;
InputStream filecontent = null;
final PrintWriter writer = response.getWriter();
try {
out = new FileOutputStream(new File(path + File.separator
+ fileName));
filecontent = filePart.getInputStream();

int read = 0;
final byte[] bytes = new byte[1024];

while ((read = filecontent.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
writer.println("New file " + fileName + " created at " + path);
} catch (FileNotFoundException fne) {
writer.println("You either did not specify a file to upload or are "
+ "trying to upload a file to a protected or nonexistent "
+ "location.");
writer.println("<br/> ERROR: " + fne.getMessage());

} finally {
if (out != null) {
out.close();
}
if (filecontent != null) {
filecontent.close();
}
if (writer != null) {
writer.close();
}
}
}

如果我像这样使用 HTML 表单发出文件请求,则上面的代码有效

<form action="UploadServlet" method="post"
enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" value="Upload File" />
</form>

所以我想在客户端使用以下代码发出相同的请求(在 android 应用程序中)

public static void uploadFile(String selectedPath, String fileType,
String fileName) {
HttpURLConnection httpUrlConnection = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
String urlString = "http://localhost:8080/FileUploadServlet1/UploadServlet";
File file = new File(selectedPath);
try {
FileInputStream fileInputStream = new FileInputStream(file);
URL url = new URL(urlString);
httpUrlConnection = (HttpURLConnection) url.openConnection();
httpUrlConnection.setDoInput(true);
httpUrlConnection.setConnectTimeout(50000000);
httpUrlConnection.setDoOutput(true);
httpUrlConnection.setUseCaches(false);
httpUrlConnection.setChunkedStreamingMode(maxBufferSize);
httpUrlConnection.setRequestMethod("POST");
httpUrlConnection.setRequestProperty("Connection", "Keep-Alive");
httpUrlConnection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
httpUrlConnection.setRequestProperty("filename", fileName);
httpUrlConnection.setRequestProperty("filetype", fileType);

dataOutputStream = new DataOutputStream(
httpUrlConnection.getOutputStream());
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
int offset = 0;
bytesRead = fileInputStream.read(buffer, offset, bufferSize);
while (bytesRead > 0) {
dataOutputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
fileInputStream.close();
dataOutputStream.flush();
dataOutputStream.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
try {
dataInputStream = new DataInputStream(
httpUrlConnection.getInputStream());
dataInputStream.close();
} catch (IOException ioex) {
ioex.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}

}

但在这种情况下,我在这条线上遇到了异常

final String fileName = getFileName(filePart);

我也使用过 Apache 文件上传库 但在那种情况下我也没有得到这一行的值(value)

列出 fileItems = upload.parseRequest(request);

那么我应该在 uploadFile() 方法中做些什么改变请帮忙。

最佳答案

这是在服务器上上传文件的示例代码。您需要外部库才能使其正常工作,例如 apache commonhttp mimehttp core。使用外部库,代码非常容易理解和清理。

public static String post(String url,String[] args) throws UnsupportedEncodingException {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);

FileBody bin = new FileBody(new File(args[0]));//"/sdcard/DCIM/cam.jpg"));//
long size = bin.getContentLength();

MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("image1", bin);
String content = "-";
try {
httpPost.setEntity(reqEntity);
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity ent = response.getEntity();
InputStream st = ent.getContent();
StringWriter writer = new StringWriter();
IOUtils.copy(st, writer);
content = writer.toString();

} catch (IOException e) {
return "false";
}
return content;
}

关于java - 使用Java代码创建文件上传请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17759075/

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