gpt4 book ai didi

java - 上传任何文件到服务器

转载 作者:行者123 更新时间:2023-12-02 02:46:05 26 4
gpt4 key购买 nike

我想编写一个函数,将任何文件上传到我的服务器。我在互联网上进行了搜索,但在不使用任何外部库的情况下没有发现任何有用的东西。有什么建议吗?

最佳答案

试试这个

public int uploadFile(String sourceFileUri, String destUri)
{
String fileName = sourceFileUri;
Log.e("YOUR_TAG", "uploading file: " + sourceFileUri);

HttpURLConnection conn;
DataOutputStream dos;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);

if (!sourceFile.isFile() && !sourceFile.exists())
{
Log.e(YOUR_TAG, "Source File not exist :" + imagepath);
return 0;

} else {

try
{
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(destUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);

while (bytesRead > 0)
{
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}

dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i(YOUR_TAG, "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);

if (serverResponseCode == 200)
{
Log.d(YOUR_TAG, "success: " + sourceFileUri);
//do your stuff here
}
fileInputStream.close();
dos.flush();
dos.close();

} catch (MalformedURLException ex) {

ex.printStackTrace();
Log.e(YOUR_TAG, "error: " + ex.getMessage(), ex);

} catch (Exception e) {

e.printStackTrace();
Log.e(YOUR_TAG, "Exception : " + e.getMessage(), e);

}
return serverResponseCode;
}
}

关于java - 上传任何文件到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44561703/

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