我正在上传文件。我想获取文件并保存到我的本地系统。为此我在java中使用spring surf webscripts。任何人都可以告诉我如何获取我的文件。
这是我的ftl文件:
<form name="frmUpload" id="frmUpload"action="${url.context}/upload" enctype="multipart/form-data" method="get">
<input type="file" size="40" id="toBeUploaded" name="toBeUploaded" tabindex="2" onchange = "document.getElementById('frmUpload').submit()"required />
</form>
我正在创建一个支持的java webscript来获取此文件。这是我的java代码。
public class Upload extends DeclarativeWebScript{
protected ServiceRegistry serviceRegistry;
private static final long serialVersionUID = 1L;
private String fileName;
private String filePath;
private File toBeUploaded;
private String toBeUploadedFileName = "";
private String toBeUploadedContentType;
/** Multi-part form data, if provided */
private FormData formData;
/** Content read from the inputstream */
private Content content = null;
// upload settings
private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB
private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB
@Override
protected Map executeImpl(WebScriptRequest req,Status status) {
System.out.println("backed webscript called");
Boolean isMultipart = false;
String fileName = req.getParameter("toBeUploaded");
if(fileName == null){
System.out.println("File Name is null");
}else{
System.out.println("File Name is :" + fileName);
}
HttpServletRequest request = ServletUtil.getRequest();
String file = request.getParameter("toBeUploaded");
File file2 = new File(file);
String filePath = request.getSession().getServletContext().getRealPath("/");
File fileToCreate = new File(filePath, this.toBeUploadedFileName);
System.out.println("filepath "+filePath);
try {
FileUtils.copyFile(file2, fileToCreate);
//validateBundle(fileToCreate);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("filetocreate "+fileToCreate);
}
}
文件名正在正常,但它正在抛出FileNotFoundExeption。这是stacktrace
java.io.FileNotFoundException: Source 'test.jar' does not exist
at org.apache.commons.io.FileUtils.copyFile(FileUtils.java:637)
at org.apache.commons.io.FileUtils.copyFile(FileUtils.java:607)
答案 0 :(得分:1)
要获取上传的表单,您需要通过FormData对象进行操作。您的代码将类似于:
// Get our multipart form
final ResourceBundle rb = getResources();
final FormData form = (FormData)req.parseContent();
if (form == null || !form.getIsMultiPart())
{
throw new ResourceBundleWebScriptException(Status.STATUS_BAD_REQUEST, rb, ERROR_BAD_FORM);
}
// Find the File Upload file, and process the contents
boolean processed = false;
for (FormData.FormField field : form.getFields())
{
if (field.getIsFile())
{
// Logic to process/save the file data here
processUpload(
field.getInputStream(),
field.getFilename());
processed = true;
break;
}
}
// Object if we didn't get a file
if (!processed)
{
throw new ResourceBundleWebScriptException(Status.STATUS_BAD_REQUEST, rb, ERROR_NO_FILE);
}
如果你确定上传的字段名称,你可以短路一些逻辑位