我最近做這個使用Spring Web MVC框架和Apache通用FileUpload:
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
(...)
@RequestMapping(method = RequestMethod.POST)
public ModelAndView uploadFile(HttpServletRequest request, HttpServletResponse response) {
ModelAndView modelAndView = new ModelAndView("view");
if (ServletFileUpload.isMultipartContent(request)) {
handleMultiPartContent(request);
}
return modelAndView;
}
private void handleMultiPartContent(HttpServletRequest request) {
ServletFileUpload upload = new ServletFileUpload();
upload.setFileSizeMax(2097152); // 2 Mb
try {
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
if (!item.isFormField()) {
File tempFile = saveFile(item);
// process the file
}
}
}
catch (FileUploadException e) {
LOG.debug("Error uploading file", e);
}
catch (IOException e) {
LOG.debug("Error uploading file", e);
}
}
private File saveFile(FileItemStream item) {
InputStream in = null;
OutputStream out = null;
try {
in = item.openStream();
File tmpFile = File.createTempFile("tmp_upload", null);
tmpFile.deleteOnExit();
out = new FileOutputStream(tmpFile);
long bytes = 0;
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
bytes += len;
}
LOG.debug(String.format("Saved %s bytes to %s ", bytes, tmpFile.getCanonicalPath()));
return tmpFile;
}
catch (IOException e) {
LOG.debug("Could not save file", e);
Throwable cause = e.getCause();
if (cause instanceof FileSizeLimitExceededException) {
LOG.debug("File too large", e);
}
else {
LOG.debug("Technical error", e);
}
return null;
}
finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
catch (IOException e) {
LOG.debug("Could not close stream", e);
}
}
}
這將上傳文件到一個臨時文件。
如果你並不需要在所有上傳的低級別的控制,它是非常簡單的使用CommonsMultipartResolver:
<!-- Configure the multipart resolver -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="2097152"/>
</bean>
在JSP示例形式:
<form:form modelAttribute="myForm" method="post" enctype="multipart/form-data">
<form:input path="bean.uploadedFile" type="file"/>
</form>
bean中的uploadDocument屬於org.springframework.web.multipart.CommonsMultipartFile類型,可直接在控制器中訪問(multipartResolver自動分析每個多部分請求)
所以你想使用JAVA或PHP?因爲你的HTML表單提交給PHP ... – GEMI
我想用java來提交表單。 – coolboycsaba
html表單不在我的網站上,我需要每天至少提交一次或兩次該表單,並且由於這個原因,我想自動填寫並提交表單給我使用的腳本 – coolboycsaba