在过去的几天里,我一直在解决这个问题,并且没有其他帖子对您有所帮助。我正在尝试在看起来像这样的HTML表单上上传文件(它包含其他字段):
<input type =“ text” id =“ prenom” name =“ fname”占位符=“ Prenom”> <br> <br> <input type =“ text” id =“ nom” name =“ fname”占位符=“ 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调用中遇到了一个错误(我正在通过对另一个servlet的另一个ajax调用来处理其他字段,由于它们是文本字段,因此可以正常工作)。
我觉得问题一定是在服务器端,因为我在客户端使用的代码无处不在。
任何提示将不胜感激!
谢谢!
编辑:实际与此代码文件已正确保存,但仍然存在Ajax错误
问题是每个都带有.done的双重ajax调用,通过不希望从文件上载ajax调用中得到答案,并期望其余提交的信息中有一个(将用户重定向到另一个页面)来解决此问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句