用java 写一个附件上传的代码
时间: 2024-06-10 22:08:51 浏览: 80
好的,以下是一个简单的 Java 附件上传代码示例:
```
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;
public class FileUtil {
public static void uploadFile(MultipartFile file) throws IOException {
String fileName = file.getOriginalFilename();
String filePath = "path/to/save/uploaded/files/";
File dest = new File(filePath + fileName);
FileUtils.copyInputStreamToFile(file.getInputStream(), dest);
}
}
```
你可以修改 `filePath` 变量来指定保存上传附件的目录,这个目录需要保证对应的文件夹存在并且有写入权限。在示例代码中,我们使用了 Apache Commons IO 库提供的 `FileUtils` 类来简化文件操作。使用这个代码,你就能够实现基本的附件上传功能。希望对你有所帮助。
相关问题
用java写一个上传附件的代码,支持多附件上传
A:以下是一个简单的用java写的多附件上传代码。首先需要依赖于相关的jar包(如commons-fileupload和commons-io),然后通过Servlet处理上传的请求:
```java
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
@WebServlet("/upload")
@MultipartConfig
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 设置上传文件的保存路径
String savePath = request.getServletContext().getRealPath("/uploads");
// 创建文件上传处理器
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024 * 1024);
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload uploader = new ServletFileUpload(factory);
uploader.setFileSizeMax(1024 * 1024 * 10); // 10 MB
uploader.setSizeMax(1024 * 1024 * 100); // 100 MB
try {
// 解析请求,获取上传的文件列表
List<FileItem> fileItems = uploader.parseRequest(request);
// 遍历文件列表
for (FileItem fileItem : fileItems) {
if (!fileItem.isFormField()) { // 如果是文件类型
String fileName = new File(fileItem.getName()).getName();
String filePath = savePath + File.separator + fileName;
File storeFile = new File(filePath);
// 保存文件到硬盘
fileItem.write(storeFile);
}
}
request.setAttribute("message", "文件上传成功!");
} catch (Exception ex) {
request.setAttribute("message", "上传失败: " + ex.getMessage());
}
// 跳转到上传结果页面
request.getRequestDispatcher("/result.jsp").forward(request, response);
}
}
```
上述代码实现了从请求中解析出上传的文件,遍历文件列表并将它们保存到硬盘的功能。其中,`@MultipartConfig`注解告诉Servlet容器这是一个支持文件上传的Servlet,`ServletFileUpload`类是Apache Commons FileUpload库提供的功能强大的上传处理器。
Java写一段附件上传
这里是Java写一段附件上传的示例代码:
```
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;
public class FileUploader {
private static final String BOUNDARY = "---------------------------" + UUID.randomUUID().toString().replaceAll("-", "");
public static void main(String[] args) throws IOException {
File file = new File("path/to/file");
String url = "http://example.com/upload";
String contentType = "application/octet-stream";
upload(file, url, contentType);
}
public static void upload(File file, String url, String contentType) throws IOException {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
String fileName = file.getName();
String fieldName = "file";
StringBuilder sb = new StringBuilder();
sb.append("--").append(BOUNDARY).append("\r\n")
.append("Content-Disposition: form-data; name=\"").append(fieldName).append("\"; filename=\"").append(fileName).append("\"\r\n")
.append("Content-Type: ").append(contentType).append("\r\n")
.append("\r\n");
byte[] headerBytes = sb.toString().getBytes();
InputStream is = new FileInputStream(file);
byte[] dataBytes = is.readAllBytes();
byte[] footerBytes = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
conn.setRequestProperty("Content-Length", String.valueOf(headerBytes.length + dataBytes.length + footerBytes.length));
conn.getOutputStream().write(headerBytes);
conn.getOutputStream().write(dataBytes);
conn.getOutputStream().write(footerBytes);
int responseCode = conn.getResponseCode();
System.out.println("Response code: " + responseCode);
}
}
```
使用时,需要替换以下部分:
- `path/to/file`:文件路径
- `http://example.com/upload`:上传接口地址
- `application/octet-stream`:文件类型
该代码使用`HttpURLConnection`发送POST请求,将文件作为multipart/form-data形式的请求体发送。请求体的格式如下:
```
--boundary
Content-Disposition: form-data; name="field_name"; filename="file_name"
Content-Type: content_type
file_data
--boundary--
```
其中,`boundary`为随机生成的字符串,用于分隔请求体的各个部分;`field_name`为文件字段名,可以自定义;`file_name`为文件名;`content_type`为文件类型,根据实际情况设置;`file_data`为文件内容。最后,需要计算请求体的长度,并设置`Content-Length`请求头。上传完成后,可以根据响应码判断上传是否成功。
阅读全文
相关推荐












