我需要java实现从浏览器获取文件并上传到OSS的代码
时间: 2024-06-12 08:07:21 浏览: 214
以下是Java实现从浏览器获取文件并上传到OSS的代码示例:
```java
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String ACCESS_KEY_ID = "your_access_key_id";
private static final String ACCESS_KEY_SECRET = "your_access_key_secret";
private static final String ENDPOINT = "your_endpoint";
private static final String BUCKET_NAME = "your_bucket_name";
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
// 解析上传的文件
@SuppressWarnings("unchecked")
java.util.List<FileItem> items = upload.parseRequest(request);
// 遍历上传的文件
for (FileItem item : items) {
if (!item.isFormField()) {
// 获取文件名
String fileName = item.getName();
// 上传到OSS
OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
ossClient.putObject(new PutObjectRequest(BUCKET_NAME, fileName, item.getInputStream()));
ossClient.shutdown();
}
}
response.getWriter().print("Upload success");
} catch (FileUploadException e) {
e.printStackTrace();
response.getWriter().print("Upload failed");
}
}
}
```
在这个示例中,我们使用了Apache Commons FileUpload库来解析上传的文件。我们遍历上传的文件并将其上传到阿里云OSS。
在上传之前,您需要将ACCESS_KEY_ID,ACCESS_KEY_SECRET,ENDPOINT和BUCKET_NAME替换为您自己的阿里云OSS凭据和桶信息。
阅读全文