![](/img/trans.png)
[英]Download textarea contents as a file using only Javascript (no server-side)
[英]Uploading file using ajax and handling it with a java servlet server-side
在过去的几天里,我一直被困在这个问题上,并且没有其他帖子有帮助。 我正在尝试在 HTML 表单上上传一个文件,该表单如下所示(它包含其他字段):
<input type="text" id="prenom" name="fname" placeholder="Prenom"><br><br> <input type="text" id="nom" name="fname" placeholder="Nom"><br><br> <input type="email" id="mail" name="fname" placeholder="Adresse mail"><br><br> <input type="file" id="file" name="file" /> </form> <br><button id="bouton-inscription" >s'inscrire</button>```
然后通过FormData将其上传到使用Ajax:
var formData = new FormData();
formData.append('file', $('#file')[0].files[0]);
$.ajax({
url: './upload',
cache: false,
processData: false,
contentType: false,
method: 'POST',
data: formData,
dataType: 'json'
})
然后,在服务器端,我想检索文件并使用 httpServlet 保存它,我正在使用我从 Oracle 文档“改编”的这段代码:
@WebServlet(name = "FileUploadServlet", urlPatterns = {"/upload"})
@MultipartConfig
public class FileUploadServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
// Create path components to save the file
final String path = "C:\\Users\\me\\Desktop";
final Part filePart = request.getPart("file");
final String fileName = "myFile";
OutputStream out = null;
InputStream filecontent = null;
final PrintWriter writer = response.getWriter();
try {
out = new FileOutputStream(new File(path + File.separator
+ fileName));
filecontent = filePart.getInputStream();
int read = 0;
final byte[] bytes = new byte[1024];
while ((read = filecontent.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
writer.println("New file " + fileName + " created at " + path);
} catch (FileNotFoundException fne) {
writer.println("You either did not specify a file to upload or are "
+ "trying to upload a file to a protected or nonexistent "
+ "location.");
writer.println("<br/> ERROR: " + fne.getMessage());
} finally {
if (out != null) {
out.close();
}
if (filecontent != null) {
filecontent.close();
}
if (writer != null) {
writer.close();
}
}
}
但是我在 Ajax 调用中遇到一个错误(我正在处理其他字段,另一个 ajax 调用另一个 servlet 工作得很好,因为它们是文本字段)。
我觉得问题一定是服务器端的,因为我在客户端使用的代码我随处可见。
任何提示将不胜感激!
谢谢!
编辑:实际上使用此代码文件已正确保存,但仍有 Ajax 错误
问题是双 ajax 调用,每个调用都带有 a.done ,通过不期望文件上传 ajax 调用的答案来修复它,并期望来自提交的 info.done 的 Z65E8800B5C68068AFCZ82A 的一个(这会将用户重定向到另一个页面)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.